webpack.config.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /* -----------------------------------------------------------------------------
  2. | Copyright (c) Jupyter Development Team.
  3. | Distributed under the terms of the Modified BSD License.
  4. |----------------------------------------------------------------------------*/
  5. const plib = require('path');
  6. const fs = require('fs-extra');
  7. const Handlebars = require('handlebars');
  8. const HtmlWebpackPlugin = require('html-webpack-plugin');
  9. const webpack = require('webpack');
  10. const merge = require('webpack-merge').default;
  11. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
  12. .BundleAnalyzerPlugin;
  13. const baseConfig = require('@jupyterlab/builder/lib/webpack.config.base');
  14. const { ModuleFederationPlugin } = webpack.container;
  15. const Build = require('@jupyterlab/builder').Build;
  16. const WPPlugin = require('@jupyterlab/builder').WPPlugin;
  17. const package_data = require('./package.json');
  18. // Handle the extensions.
  19. const jlab = package_data.jupyterlab;
  20. const { extensions, mimeExtensions, externalExtensions } = jlab;
  21. // Add external extensions to the extensions/mimeExtensions data as
  22. // appropriate
  23. for (const pkg in externalExtensions) {
  24. const {
  25. jupyterlab: { extension, mimeExtension }
  26. } = require(`${pkg}/package.json`);
  27. if (extension !== undefined) {
  28. extensions[pkg] = extension === true ? '' : extension;
  29. }
  30. if (mimeExtension !== undefined) {
  31. mimeExtensions[pkg] = mimeExtension === true ? '' : mimeExtension;
  32. }
  33. }
  34. // Deduplicated list of extension package names.
  35. const extensionPackages = [
  36. ...new Set([...Object.keys(extensions), ...Object.keys(mimeExtensions)])
  37. ];
  38. // Ensure a clear build directory.
  39. const buildDir = plib.resolve(jlab.buildDir);
  40. if (fs.existsSync(buildDir)) {
  41. fs.removeSync(buildDir);
  42. }
  43. fs.ensureDirSync(buildDir);
  44. const outputDir = plib.resolve(jlab.outputDir);
  45. // Build the assets
  46. const extraConfig = Build.ensureAssets({
  47. // Deduplicate the extension package names
  48. packageNames: extensionPackages,
  49. output: outputDir
  50. });
  51. // Create the entry point and other assets in build directory.
  52. const source = fs.readFileSync('index.js').toString();
  53. const template = Handlebars.compile(source);
  54. const extData = {
  55. jupyterlab_extensions: extensions,
  56. jupyterlab_mime_extensions: mimeExtensions
  57. };
  58. fs.writeFileSync(plib.join(buildDir, 'index.out.js'), template(extData));
  59. // Create the bootstrap file that loads federated extensions and calls the
  60. // initialization logic in index.out.js
  61. const entryPoint = plib.join(buildDir, 'bootstrap.js');
  62. fs.copySync('./bootstrap.js', entryPoint);
  63. fs.copySync('./package.json', plib.join(buildDir, 'package.json'));
  64. if (outputDir !== buildDir) {
  65. fs.copySync(
  66. plib.join(outputDir, 'style.js'),
  67. plib.join(buildDir, 'style.js')
  68. );
  69. }
  70. // Set up variables for the watch mode ignore plugins
  71. const watched = {};
  72. const ignoreCache = Object.create(null);
  73. let watchNodeModules = false;
  74. Object.keys(jlab.linkedPackages).forEach(function (name) {
  75. if (name in watched) {
  76. return;
  77. }
  78. const localPkgPath = require.resolve(plib.join(name, 'package.json'));
  79. watched[name] = plib.dirname(localPkgPath);
  80. if (localPkgPath.indexOf('node_modules') !== -1) {
  81. watchNodeModules = true;
  82. }
  83. });
  84. // Set up source-map-loader to look in watched lib dirs
  85. const sourceMapRes = Object.values(watched).reduce((res, name) => {
  86. res.push(new RegExp(name + '/lib'));
  87. return res;
  88. }, []);
  89. /**
  90. * Sync a local path to a linked package path if they are files and differ.
  91. * This is used by `jupyter lab --watch` to synchronize linked packages
  92. * and has no effect in `jupyter lab --dev-mode --watch`.
  93. */
  94. function maybeSync(localPath, name, rest) {
  95. const stats = fs.statSync(localPath);
  96. if (!stats.isFile(localPath)) {
  97. return;
  98. }
  99. const source = fs.realpathSync(plib.join(jlab.linkedPackages[name], rest));
  100. if (source === fs.realpathSync(localPath)) {
  101. return;
  102. }
  103. fs.watchFile(source, { interval: 500 }, function (curr) {
  104. if (!curr || curr.nlink === 0) {
  105. return;
  106. }
  107. try {
  108. fs.copySync(source, localPath);
  109. } catch (err) {
  110. console.error(err);
  111. }
  112. });
  113. }
  114. /**
  115. * A filter function set up to exclude all files that are not
  116. * in a package contained by the Jupyterlab repo. Used to ignore
  117. * files during a `--watch` build.
  118. */
  119. function ignored(path) {
  120. path = plib.resolve(path);
  121. if (path in ignoreCache) {
  122. // Bail if already found.
  123. return ignoreCache[path];
  124. }
  125. // Limit the watched files to those in our local linked package dirs.
  126. let ignore = true;
  127. Object.keys(watched).some(name => {
  128. const rootPath = watched[name];
  129. const contained = path.indexOf(rootPath + plib.sep) !== -1;
  130. if (path !== rootPath && !contained) {
  131. return false;
  132. }
  133. const rest = path.slice(rootPath.length);
  134. if (rest.indexOf('node_modules') === -1) {
  135. ignore = false;
  136. maybeSync(path, name, rest);
  137. }
  138. return true;
  139. });
  140. ignoreCache[path] = ignore;
  141. return ignore;
  142. }
  143. // Set up module federation sharing config
  144. const shared = {};
  145. // Make sure any resolutions are shared
  146. for (let [pkg, requiredVersion] of Object.entries(package_data.resolutions)) {
  147. shared[pkg] = { requiredVersion };
  148. }
  149. // Add any extension packages that are not in resolutions (i.e., installed from npm)
  150. for (let pkg of extensionPackages) {
  151. if (!shared[pkg]) {
  152. shared[pkg] = {
  153. requiredVersion: require(`${pkg}/package.json`).version
  154. };
  155. }
  156. }
  157. // Add dependencies and sharedPackage config from extension packages if they
  158. // are not already in the shared config. This means that if there is a
  159. // conflict, the resolutions package version is the one that is shared.
  160. const extraShared = [];
  161. for (let pkg of extensionPackages) {
  162. let pkgShared = {};
  163. let {
  164. dependencies = {},
  165. jupyterlab: { sharedPackages = {} } = {}
  166. } = require(`${pkg}/package.json`);
  167. for (let [dep, requiredVersion] of Object.entries(dependencies)) {
  168. if (!shared[dep]) {
  169. pkgShared[dep] = { requiredVersion };
  170. }
  171. }
  172. // Overwrite automatic dependency sharing with custom sharing config
  173. for (let [dep, config] of Object.entries(sharedPackages)) {
  174. if (config === false) {
  175. delete pkgShared[dep];
  176. } else {
  177. if ('bundled' in config) {
  178. config.import = config.bundled;
  179. delete config.bundled;
  180. }
  181. pkgShared[dep] = config;
  182. }
  183. }
  184. extraShared.push(pkgShared);
  185. }
  186. // Now merge the extra shared config
  187. const mergedShare = {};
  188. for (let sharedConfig of extraShared) {
  189. for (let [pkg, config] of Object.entries(sharedConfig)) {
  190. // Do not override the basic share config from resolutions
  191. if (shared[pkg]) {
  192. continue;
  193. }
  194. // Add if we haven't seen the config before
  195. if (!mergedShare[pkg]) {
  196. mergedShare[pkg] = config;
  197. continue;
  198. }
  199. // Choose between the existing config and this new config. We do not try
  200. // to merge configs, which may yield a config no one wants
  201. let oldConfig = mergedShare[pkg];
  202. // if the old one has import: false, use the new one
  203. if (oldConfig.import === false) {
  204. mergedShare[pkg] = config;
  205. }
  206. }
  207. }
  208. Object.assign(shared, mergedShare);
  209. // Transform any file:// requiredVersion to the version number from the
  210. // imported package. This assumes (for simplicity) that the version we get
  211. // importing was installed from the file.
  212. for (let [pkg, { requiredVersion }] of Object.entries(shared)) {
  213. if (requiredVersion && requiredVersion.startsWith('file:')) {
  214. shared[pkg].requiredVersion = require(`${pkg}/package.json`).version;
  215. }
  216. }
  217. // Add singleton package information
  218. for (let pkg of jlab.singletonPackages) {
  219. shared[pkg].singleton = true;
  220. }
  221. const plugins = [
  222. new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
  223. verbose: true,
  224. exclude(instance) {
  225. // ignore known duplicates
  226. return ['domelementtype', 'hash-base', 'inherits'].includes(
  227. instance.name
  228. );
  229. }
  230. }),
  231. new HtmlWebpackPlugin({
  232. chunksSortMode: 'none',
  233. template: plib.join(__dirname, 'templates', 'template.html'),
  234. title: jlab.name || 'JupyterLab'
  235. }),
  236. // custom plugin for ignoring files during a `--watch` build
  237. new WPPlugin.FilterWatchIgnorePlugin(ignored),
  238. // custom plugin that copies the assets to the static directory
  239. new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  240. new ModuleFederationPlugin({
  241. library: {
  242. type: 'var',
  243. name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
  244. },
  245. name: 'CORE_FEDERATION',
  246. shared
  247. })
  248. ];
  249. if (process.argv.includes('--analyze')) {
  250. plugins.push(new BundleAnalyzerPlugin());
  251. }
  252. module.exports = [
  253. merge(baseConfig, {
  254. mode: 'development',
  255. entry: {
  256. main: ['./publicpath', 'whatwg-fetch', entryPoint]
  257. },
  258. output: {
  259. path: plib.resolve(buildDir),
  260. publicPath: '{{page_config.fullStaticUrl}}/',
  261. filename: '[name].[contenthash].js'
  262. },
  263. optimization: {
  264. splitChunks: {
  265. chunks: 'all',
  266. cacheGroups: {
  267. jlab_core: {
  268. test: /[\\/]node_modules[\\/]@(jupyterlab|lumino)[\\/]/,
  269. name: 'jlab_core'
  270. }
  271. }
  272. }
  273. },
  274. module: {
  275. rules: [
  276. {
  277. test: /\.js$/,
  278. include: sourceMapRes,
  279. use: ['source-map-loader'],
  280. enforce: 'pre'
  281. }
  282. ]
  283. },
  284. devtool: 'inline-source-map',
  285. externals: ['node-fetch', 'ws'],
  286. plugins
  287. })
  288. ].concat(extraConfig);
  289. // Needed to watch changes in linked extensions in node_modules
  290. // (jupyter lab --watch)
  291. // See https://github.com/webpack/webpack/issues/11612
  292. if (watchNodeModules) {
  293. module.exports[0].snapshot = { managedPaths: [] };
  294. }
  295. const logPath = plib.join(buildDir, 'build_log.json');
  296. fs.writeFileSync(logPath, JSON.stringify(module.exports, null, ' '));