webpack.config.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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/buildutils/lib/webpack.config.base');
  14. const { ModuleFederationPlugin } = webpack.container;
  15. const Build = require('@jupyterlab/buildutils').Build;
  16. const WPPlugin = require('@jupyterlab/buildutils').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. Object.keys(jlab.linkedPackages).forEach(function(name) {
  96. if (name in watched) {
  97. return;
  98. }
  99. const localPkgPath = require.resolve(plib.join(name, 'package.json'));
  100. watched[name] = plib.dirname(localPkgPath);
  101. });
  102. // Set up source-map-loader to look in watched lib dirs
  103. const sourceMapRes = Object.values(watched).reduce((res, name) => {
  104. res.push(new RegExp(name + '/lib'));
  105. return res;
  106. }, []);
  107. /**
  108. * Sync a local path to a linked package path if they are files and differ.
  109. * This is used by `jupyter lab --watch` to synchronize linked packages
  110. * and has no effect in `jupyter lab --dev-mode --watch`.
  111. */
  112. function maybeSync(localPath, name, rest) {
  113. const stats = fs.statSync(localPath);
  114. if (!stats.isFile(localPath)) {
  115. return;
  116. }
  117. const source = fs.realpathSync(plib.join(jlab.linkedPackages[name], rest));
  118. if (source === fs.realpathSync(localPath)) {
  119. return;
  120. }
  121. fs.watchFile(source, { interval: 500 }, function(curr) {
  122. if (!curr || curr.nlink === 0) {
  123. return;
  124. }
  125. try {
  126. fs.copySync(source, localPath);
  127. } catch (err) {
  128. console.error(err);
  129. }
  130. });
  131. }
  132. /**
  133. * A filter function set up to exclude all files that are not
  134. * in a package contained by the Jupyterlab repo. Used to ignore
  135. * files during a `--watch` build.
  136. */
  137. function ignored(path) {
  138. path = plib.resolve(path);
  139. if (path in ignoreCache) {
  140. // Bail if already found.
  141. return ignoreCache[path];
  142. }
  143. // Limit the watched files to those in our local linked package dirs.
  144. let ignore = true;
  145. Object.keys(watched).some(name => {
  146. const rootPath = watched[name];
  147. const contained = path.indexOf(rootPath + plib.sep) !== -1;
  148. if (path !== rootPath && !contained) {
  149. return false;
  150. }
  151. const rest = path.slice(rootPath.length);
  152. if (rest.indexOf('node_modules') === -1) {
  153. ignore = false;
  154. maybeSync(path, name, rest);
  155. }
  156. return true;
  157. });
  158. ignoreCache[path] = ignore;
  159. return ignore;
  160. }
  161. const plugins = [
  162. new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
  163. verbose: true,
  164. exclude(instance) {
  165. // ignore known duplicates
  166. return ['domelementtype', 'hash-base', 'inherits'].includes(
  167. instance.name
  168. );
  169. }
  170. }),
  171. new HtmlWebpackPlugin({
  172. chunksSortMode: 'none',
  173. template: plib.join(__dirname, 'templates', 'template.html'),
  174. title: jlab.name || 'JupyterLab'
  175. }),
  176. new webpack.ids.HashedModuleIdsPlugin(),
  177. // custom plugin for ignoring files during a `--watch` build
  178. new WPPlugin.FilterWatchIgnorePlugin(ignored),
  179. // custom plugin that copies the assets to the static directory
  180. new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  181. new ModuleFederationPlugin({
  182. library: {
  183. type: 'var',
  184. name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
  185. },
  186. name: 'CORE_FEDERATION',
  187. shared: {
  188. ...package_data.resolutions,
  189. ...singletons
  190. }
  191. })
  192. ];
  193. if (process.argv.includes('--analyze')) {
  194. plugins.push(new BundleAnalyzerPlugin());
  195. }
  196. module.exports = [
  197. merge(baseConfig, {
  198. mode: 'development',
  199. entry: {
  200. main: ['whatwg-fetch', entryPoint]
  201. },
  202. output: {
  203. path: plib.resolve(buildDir),
  204. publicPath: 'static/lab/',
  205. filename: '[name].[chunkhash].js'
  206. },
  207. optimization: {
  208. splitChunks: {
  209. chunks: 'all'
  210. }
  211. },
  212. module: {
  213. rules: [
  214. {
  215. test: /\.js$/,
  216. include: sourceMapRes,
  217. use: ['source-map-loader'],
  218. enforce: 'pre'
  219. }
  220. ]
  221. },
  222. devtool: 'inline-source-map',
  223. externals: ['node-fetch', 'ws'],
  224. plugins
  225. })
  226. ].concat(extraConfig);
  227. const logPath = plib.join(buildDir, 'build_log.json');
  228. fs.writeFileSync(logPath, JSON.stringify(module.exports, null, ' '));