webpack.config.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 = jlab.extensions;
  21. const mimeExtensions = jlab.mimeExtensions;
  22. const { externalExtensions } = jlab;
  23. const packageNames = Object.keys(mimeExtensions).concat(
  24. Object.keys(extensions),
  25. Object.keys(externalExtensions)
  26. );
  27. // go throught each external extension
  28. // add to mapping of extension and mime extensions, of package name
  29. // to path of the extension.
  30. for (const key in externalExtensions) {
  31. const {
  32. jupyterlab: { extension, mimeExtension }
  33. } = require(`${key}/package.json`);
  34. if (extension !== undefined) {
  35. extensions[key] = extension === true ? '' : extension;
  36. }
  37. if (mimeExtension !== undefined) {
  38. mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension;
  39. }
  40. }
  41. // Ensure a clear build directory.
  42. const buildDir = plib.resolve(jlab.buildDir);
  43. if (fs.existsSync(buildDir)) {
  44. fs.removeSync(buildDir);
  45. }
  46. fs.ensureDirSync(buildDir);
  47. const outputDir = plib.resolve(jlab.outputDir);
  48. // Build the assets
  49. const extraConfig = Build.ensureAssets({
  50. packageNames: packageNames,
  51. output: outputDir
  52. });
  53. // Build up singleton metadata for module federation.
  54. const singletons = {};
  55. package_data.jupyterlab.singletonPackages.forEach(element => {
  56. singletons[element] = { singleton: true };
  57. });
  58. // Go through each external extension
  59. // add to mapping of extension and mime extensions, of package name
  60. // to path of the extension.
  61. for (const key in externalExtensions) {
  62. const {
  63. jupyterlab: { extension, mimeExtension }
  64. } = require(`${key}/package.json`);
  65. if (extension !== undefined) {
  66. extensions[key] = extension === true ? '' : extension;
  67. }
  68. if (mimeExtension !== undefined) {
  69. mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension;
  70. }
  71. }
  72. // Create the entry point file.
  73. const source = fs.readFileSync('index.js').toString();
  74. const template = Handlebars.compile(source);
  75. const extData = {
  76. jupyterlab_extensions: extensions,
  77. jupyterlab_mime_extensions: mimeExtensions
  78. };
  79. const result = template(extData);
  80. fs.writeFileSync(plib.join(buildDir, 'index.out.js'), result);
  81. fs.copySync('./package.json', plib.join(buildDir, 'package.json'));
  82. if (outputDir !== buildDir) {
  83. fs.copySync(
  84. plib.join(outputDir, 'imports.css'),
  85. plib.join(buildDir, 'imports.css')
  86. );
  87. }
  88. // Make a bootstrap entrypoint
  89. const entryPoint = plib.join(buildDir, 'bootstrap.js');
  90. const bootstrap = 'import("./index.out.js");';
  91. fs.writeFileSync(entryPoint, bootstrap);
  92. // Set up variables for the watch mode ignore plugins
  93. const watched = {};
  94. const ignoreCache = Object.create(null);
  95. let watchNodeModules = false;
  96. Object.keys(jlab.linkedPackages).forEach(function (name) {
  97. if (name in watched) {
  98. return;
  99. }
  100. const localPkgPath = require.resolve(plib.join(name, 'package.json'));
  101. watched[name] = plib.dirname(localPkgPath);
  102. if (localPkgPath.indexOf('node_modules') !== -1) {
  103. watchNodeModules = true;
  104. }
  105. });
  106. // Set up source-map-loader to look in watched lib dirs
  107. const sourceMapRes = Object.values(watched).reduce((res, name) => {
  108. res.push(new RegExp(name + '/lib'));
  109. return res;
  110. }, []);
  111. /**
  112. * Sync a local path to a linked package path if they are files and differ.
  113. * This is used by `jupyter lab --watch` to synchronize linked packages
  114. * and has no effect in `jupyter lab --dev-mode --watch`.
  115. */
  116. function maybeSync(localPath, name, rest) {
  117. const stats = fs.statSync(localPath);
  118. if (!stats.isFile(localPath)) {
  119. return;
  120. }
  121. const source = fs.realpathSync(plib.join(jlab.linkedPackages[name], rest));
  122. if (source === fs.realpathSync(localPath)) {
  123. return;
  124. }
  125. fs.watchFile(source, { interval: 500 }, function (curr) {
  126. if (!curr || curr.nlink === 0) {
  127. return;
  128. }
  129. try {
  130. fs.copySync(source, localPath);
  131. } catch (err) {
  132. console.error(err);
  133. }
  134. });
  135. }
  136. /**
  137. * A filter function set up to exclude all files that are not
  138. * in a package contained by the Jupyterlab repo. Used to ignore
  139. * files during a `--watch` build.
  140. */
  141. function ignored(path) {
  142. path = plib.resolve(path);
  143. if (path in ignoreCache) {
  144. // Bail if already found.
  145. return ignoreCache[path];
  146. }
  147. // Limit the watched files to those in our local linked package dirs.
  148. let ignore = true;
  149. Object.keys(watched).some(name => {
  150. const rootPath = watched[name];
  151. const contained = path.indexOf(rootPath + plib.sep) !== -1;
  152. if (path !== rootPath && !contained) {
  153. return false;
  154. }
  155. const rest = path.slice(rootPath.length);
  156. if (rest.indexOf('node_modules') === -1) {
  157. ignore = false;
  158. maybeSync(path, name, rest);
  159. }
  160. return true;
  161. });
  162. ignoreCache[path] = ignore;
  163. return ignore;
  164. }
  165. const plugins = [
  166. new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
  167. verbose: true,
  168. exclude(instance) {
  169. // ignore known duplicates
  170. return ['domelementtype', 'hash-base', 'inherits'].includes(
  171. instance.name
  172. );
  173. }
  174. }),
  175. new HtmlWebpackPlugin({
  176. chunksSortMode: 'none',
  177. template: plib.join(__dirname, 'templates', 'template.html'),
  178. title: jlab.name || 'JupyterLab'
  179. }),
  180. // custom plugin for ignoring files during a `--watch` build
  181. new WPPlugin.FilterWatchIgnorePlugin(ignored),
  182. // custom plugin that copies the assets to the static directory
  183. new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  184. new ModuleFederationPlugin({
  185. library: {
  186. type: 'var',
  187. name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
  188. },
  189. name: 'CORE_FEDERATION',
  190. shared: {
  191. ...package_data.resolutions,
  192. ...singletons
  193. }
  194. })
  195. ];
  196. if (process.argv.includes('--analyze')) {
  197. plugins.push(new BundleAnalyzerPlugin());
  198. }
  199. module.exports = [
  200. merge(baseConfig, {
  201. mode: 'development',
  202. entry: {
  203. main: ['./publicpath', 'whatwg-fetch', entryPoint]
  204. },
  205. output: {
  206. path: plib.resolve(buildDir),
  207. publicPath: '{{page_config.fullStaticUrl}}/',
  208. filename: '[name].[contenthash].js'
  209. },
  210. optimization: {
  211. splitChunks: {
  212. chunks: 'all'
  213. }
  214. },
  215. module: {
  216. rules: [
  217. {
  218. test: /\.js$/,
  219. include: sourceMapRes,
  220. use: ['source-map-loader'],
  221. enforce: 'pre'
  222. }
  223. ]
  224. },
  225. devtool: 'inline-source-map',
  226. externals: ['node-fetch', 'ws'],
  227. plugins
  228. })
  229. ].concat(extraConfig);
  230. // Needed to watch changes in linked extensions in node_modules
  231. // (jupyter lab --watch)
  232. // See https://github.com/webpack/webpack/issues/11612
  233. if (watchNodeModules) {
  234. module.exports[0].snapshot = { managedPaths: [] };
  235. }
  236. const logPath = plib.join(buildDir, 'build_log.json');
  237. fs.writeFileSync(logPath, JSON.stringify(module.exports, null, ' '));