webpack.config.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 key in externalExtensions) {
  24. const {
  25. jupyterlab: { extension, mimeExtension }
  26. } = require(`${key}/package.json`);
  27. if (extension !== undefined) {
  28. extensions[key] = extension === true ? '' : extension;
  29. }
  30. if (mimeExtension !== undefined) {
  31. mimeExtensions[key] = 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, 'imports.css'),
  67. plib.join(buildDir, 'imports.css')
  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 [key, requiredVersion] of Object.entries(package_data.resolutions)) {
  147. // eager so that built-in extensions can be bundled together into just a few
  148. // js files to load
  149. shared[key] = { requiredVersion, eager: true };
  150. }
  151. // Add any extension packages that are not in resolutions (i.e., installed from npm)
  152. for (let pkg of extensionPackages) {
  153. if (shared[pkg] === undefined) {
  154. shared[pkg] = {
  155. requiredVersion: require(`${pkg}/package.json`).version,
  156. eager: true
  157. };
  158. }
  159. }
  160. // Add dependencies and sharedPackage config from extension packages if they
  161. // are not already in the shared config. This means that if there is a
  162. // conflict, the resolutions package version is the one that is shared.
  163. extraShared = [];
  164. for (let pkg of extensionPackages) {
  165. let pkgShared = {};
  166. let {
  167. dependencies = {},
  168. jupyterlab: { sharedPackages = {} } = {}
  169. } = require(`${pkg}/package.json`);
  170. for (let [dep, requiredVersion] of Object.entries(dependencies)) {
  171. if (!shared[dep]) {
  172. pkgShared[dep] = { requiredVersion, eager: true };
  173. }
  174. }
  175. // Overwrite automatic dependency sharing with custom sharing config
  176. for (let [pkg, config] of Object.entries(sharedPackages)) {
  177. if (config === false) {
  178. delete pkgShared[pkg];
  179. } else {
  180. if ('bundled' in config) {
  181. config.import = config.bundled;
  182. delete config.bundled;
  183. }
  184. pkgShared[pkg] = config;
  185. }
  186. }
  187. extraShared.push(pkgShared);
  188. }
  189. // Now merge the extra shared config
  190. const mergedShare = {};
  191. for (let sharedConfig of extraShared) {
  192. for (let [pkg, config] of Object.entries(sharedConfig)) {
  193. // Do not override the basic share config from resolutions
  194. if (shared[pkg]) {
  195. continue;
  196. }
  197. // Add if we haven't seen the config before
  198. if (!mergedShare[pkg]) {
  199. mergedShare[pkg] = config;
  200. continue;
  201. }
  202. // Choose between the existing config and this new config. We do not try
  203. // to merge configs, which may yield a config no one wants
  204. let oldConfig = mergedShare[pkg];
  205. // if the old one has import: false, use the new one
  206. if (oldConfig.import === false) {
  207. mergedShare[pkg] = config;
  208. }
  209. }
  210. }
  211. Object.assign(shared, mergedShare);
  212. // Transform any file:// requiredVersion to the version number from the
  213. // imported package. This assumes (for simplicity) that the version we get
  214. // importing was installed from the file.
  215. for (let [key, { requiredVersion }] of Object.entries(shared)) {
  216. if (requiredVersion?.startsWith('file:')) {
  217. shared[key].requiredVersion = require(`${key}/package.json`).version;
  218. }
  219. }
  220. // Add singleton package information
  221. for (let key of jlab.singletonPackages) {
  222. shared[key].singleton = true;
  223. }
  224. const plugins = [
  225. new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
  226. verbose: true,
  227. exclude(instance) {
  228. // ignore known duplicates
  229. return ['domelementtype', 'hash-base', 'inherits'].includes(
  230. instance.name
  231. );
  232. }
  233. }),
  234. new HtmlWebpackPlugin({
  235. chunksSortMode: 'none',
  236. template: plib.join(__dirname, 'templates', 'template.html'),
  237. title: jlab.name || 'JupyterLab'
  238. }),
  239. // custom plugin for ignoring files during a `--watch` build
  240. new WPPlugin.FilterWatchIgnorePlugin(ignored),
  241. // custom plugin that copies the assets to the static directory
  242. new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  243. new ModuleFederationPlugin({
  244. library: {
  245. type: 'var',
  246. name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
  247. },
  248. name: 'CORE_FEDERATION',
  249. shared
  250. })
  251. ];
  252. if (process.argv.includes('--analyze')) {
  253. plugins.push(new BundleAnalyzerPlugin());
  254. }
  255. module.exports = [
  256. merge(baseConfig, {
  257. mode: 'development',
  258. entry: {
  259. main: ['./publicpath', 'whatwg-fetch', entryPoint]
  260. },
  261. output: {
  262. path: plib.resolve(buildDir),
  263. publicPath: '{{page_config.fullStaticUrl}}/',
  264. filename: '[name].[contenthash].js'
  265. },
  266. optimization: {
  267. splitChunks: {
  268. chunks: 'all'
  269. }
  270. },
  271. module: {
  272. rules: [
  273. {
  274. test: /\.js$/,
  275. include: sourceMapRes,
  276. use: ['source-map-loader'],
  277. enforce: 'pre'
  278. }
  279. ]
  280. },
  281. devtool: 'inline-source-map',
  282. externals: ['node-fetch', 'ws'],
  283. plugins
  284. })
  285. ].concat(extraConfig);
  286. // Needed to watch changes in linked extensions in node_modules
  287. // (jupyter lab --watch)
  288. // See https://github.com/webpack/webpack/issues/11612
  289. if (watchNodeModules) {
  290. module.exports[0].snapshot = { managedPaths: [] };
  291. }
  292. const logPath = plib.join(buildDir, 'build_log.json');
  293. fs.writeFileSync(logPath, JSON.stringify(module.exports, null, ' '));