webpack.config.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. const entryPoint = plib.join(buildDir, 'bootstrap.js');
  60. fs.writeFileSync(entryPoint, 'import("./index.out.js");');
  61. fs.copySync('./package.json', plib.join(buildDir, 'package.json'));
  62. if (outputDir !== buildDir) {
  63. fs.copySync(
  64. plib.join(outputDir, 'imports.css'),
  65. plib.join(buildDir, 'imports.css')
  66. );
  67. }
  68. // Set up variables for the watch mode ignore plugins
  69. const watched = {};
  70. const ignoreCache = Object.create(null);
  71. let watchNodeModules = false;
  72. Object.keys(jlab.linkedPackages).forEach(function (name) {
  73. if (name in watched) {
  74. return;
  75. }
  76. const localPkgPath = require.resolve(plib.join(name, 'package.json'));
  77. watched[name] = plib.dirname(localPkgPath);
  78. if (localPkgPath.indexOf('node_modules') !== -1) {
  79. watchNodeModules = true;
  80. }
  81. });
  82. // Set up source-map-loader to look in watched lib dirs
  83. const sourceMapRes = Object.values(watched).reduce((res, name) => {
  84. res.push(new RegExp(name + '/lib'));
  85. return res;
  86. }, []);
  87. /**
  88. * Sync a local path to a linked package path if they are files and differ.
  89. * This is used by `jupyter lab --watch` to synchronize linked packages
  90. * and has no effect in `jupyter lab --dev-mode --watch`.
  91. */
  92. function maybeSync(localPath, name, rest) {
  93. const stats = fs.statSync(localPath);
  94. if (!stats.isFile(localPath)) {
  95. return;
  96. }
  97. const source = fs.realpathSync(plib.join(jlab.linkedPackages[name], rest));
  98. if (source === fs.realpathSync(localPath)) {
  99. return;
  100. }
  101. fs.watchFile(source, { interval: 500 }, function (curr) {
  102. if (!curr || curr.nlink === 0) {
  103. return;
  104. }
  105. try {
  106. fs.copySync(source, localPath);
  107. } catch (err) {
  108. console.error(err);
  109. }
  110. });
  111. }
  112. /**
  113. * A filter function set up to exclude all files that are not
  114. * in a package contained by the Jupyterlab repo. Used to ignore
  115. * files during a `--watch` build.
  116. */
  117. function ignored(path) {
  118. path = plib.resolve(path);
  119. if (path in ignoreCache) {
  120. // Bail if already found.
  121. return ignoreCache[path];
  122. }
  123. // Limit the watched files to those in our local linked package dirs.
  124. let ignore = true;
  125. Object.keys(watched).some(name => {
  126. const rootPath = watched[name];
  127. const contained = path.indexOf(rootPath + plib.sep) !== -1;
  128. if (path !== rootPath && !contained) {
  129. return false;
  130. }
  131. const rest = path.slice(rootPath.length);
  132. if (rest.indexOf('node_modules') === -1) {
  133. ignore = false;
  134. maybeSync(path, name, rest);
  135. }
  136. return true;
  137. });
  138. ignoreCache[path] = ignore;
  139. return ignore;
  140. }
  141. // Set up module federation sharing config
  142. const shared = {};
  143. for (let [key, requiredVersion] of Object.entries(package_data.resolutions)) {
  144. // eager so that built-in extensions can be bundled together into just a few
  145. // js files to load
  146. shared[key] = { requiredVersion, eager: true };
  147. }
  148. // Add dependencies of extension packages if they are not already in
  149. // resolutions. This means that if there is a conflict, the resolutions
  150. // package version is the one that is shared.
  151. for (let pkg of extensionPackages) {
  152. let { dependencies } = require(`${pkg}/package.json`);
  153. for (let [dep, requiredVersion] of Object.entries(dependencies)) {
  154. if (!shared[dep]) {
  155. shared[dep] = { requiredVersion, eager: true };
  156. }
  157. }
  158. }
  159. // Transform any file:// requiredVersion to the version number from the
  160. // imported package. This assumes (for simplicity) that the version we get
  161. // importing was installed from the file.
  162. for (let [key, { requiredVersion }] of Object.entries(shared)) {
  163. if (requiredVersion.startsWith('file:')) {
  164. shared[key].requiredVersion = require(`${key}/package.json`).version;
  165. }
  166. }
  167. // Add singleton package information
  168. for (let key of jlab.singletonPackages) {
  169. shared[key].singleton = true;
  170. }
  171. const plugins = [
  172. new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
  173. verbose: true,
  174. exclude(instance) {
  175. // ignore known duplicates
  176. return ['domelementtype', 'hash-base', 'inherits'].includes(
  177. instance.name
  178. );
  179. }
  180. }),
  181. new HtmlWebpackPlugin({
  182. chunksSortMode: 'none',
  183. template: plib.join(__dirname, 'templates', 'template.html'),
  184. title: jlab.name || 'JupyterLab'
  185. }),
  186. // custom plugin for ignoring files during a `--watch` build
  187. new WPPlugin.FilterWatchIgnorePlugin(ignored),
  188. // custom plugin that copies the assets to the static directory
  189. new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  190. new ModuleFederationPlugin({
  191. library: {
  192. type: 'var',
  193. name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
  194. },
  195. name: 'CORE_FEDERATION',
  196. shared
  197. })
  198. ];
  199. if (process.argv.includes('--analyze')) {
  200. plugins.push(new BundleAnalyzerPlugin());
  201. }
  202. module.exports = [
  203. merge(baseConfig, {
  204. mode: 'development',
  205. entry: {
  206. main: ['./publicpath', 'whatwg-fetch', entryPoint]
  207. },
  208. output: {
  209. path: plib.resolve(buildDir),
  210. publicPath: '{{page_config.fullStaticUrl}}/',
  211. filename: '[name].[contenthash].js'
  212. },
  213. optimization: {
  214. splitChunks: {
  215. chunks: 'all'
  216. }
  217. },
  218. module: {
  219. rules: [
  220. {
  221. test: /\.js$/,
  222. include: sourceMapRes,
  223. use: ['source-map-loader'],
  224. enforce: 'pre'
  225. }
  226. ]
  227. },
  228. devtool: 'inline-source-map',
  229. externals: ['node-fetch', 'ws'],
  230. plugins
  231. })
  232. ].concat(extraConfig);
  233. // Needed to watch changes in linked extensions in node_modules
  234. // (jupyter lab --watch)
  235. // See https://github.com/webpack/webpack/issues/11612
  236. if (watchNodeModules) {
  237. module.exports[0].snapshot = { managedPaths: [] };
  238. }
  239. const logPath = plib.join(buildDir, 'build_log.json');
  240. fs.writeFileSync(logPath, JSON.stringify(module.exports, null, ' '));