webpack.config.js 9.3 KB

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