webpack.config.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /* -----------------------------------------------------------------------------
  2. | Copyright (c) Jupyter Development Team.
  3. | Distributed under the terms of the Modified BSD License.
  4. |----------------------------------------------------------------------------*/
  5. const path = 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 packageData = require('./package.json');
  18. // Handle the extensions.
  19. const jlab = packageData.jupyterlab;
  20. const { extensions, mimeExtensions, externalExtensions } = jlab;
  21. // Add external extensions to the extensions/mimeExtensions data as
  22. // appropriate
  23. for (const pkg in externalExtensions) {
  24. const {
  25. jupyterlab: { extension, mimeExtension }
  26. } = require(`${pkg}/package.json`);
  27. if (extension !== undefined) {
  28. extensions[pkg] = extension === true ? '' : extension;
  29. }
  30. if (mimeExtension !== undefined) {
  31. mimeExtensions[pkg] = 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 = path.resolve(jlab.buildDir);
  40. if (fs.existsSync(buildDir)) {
  41. fs.removeSync(buildDir);
  42. }
  43. fs.ensureDirSync(buildDir);
  44. const outputDir = path.resolve(jlab.outputDir);
  45. // Configuration to handle extension assets
  46. const extensionAssetConfig = Build.ensureAssets({
  47. packageNames: extensionPackages,
  48. output: outputDir
  49. });
  50. // Create the entry point and other assets in build directory.
  51. const source = fs.readFileSync('index.js').toString();
  52. const template = Handlebars.compile(source);
  53. const extData = {
  54. jupyterlab_extensions: extensions,
  55. jupyterlab_mime_extensions: mimeExtensions
  56. };
  57. fs.writeFileSync(path.join(buildDir, 'index.out.js'), template(extData));
  58. // Create the bootstrap file that loads federated extensions and calls the
  59. // initialization logic in index.out.js
  60. const entryPoint = path.join(buildDir, 'bootstrap.js');
  61. fs.copySync('./bootstrap.js', entryPoint);
  62. fs.copySync('./package.json', path.join(buildDir, 'package.json'));
  63. if (outputDir !== buildDir) {
  64. fs.copySync(
  65. path.join(outputDir, 'style.js'),
  66. path.join(buildDir, 'style.js')
  67. );
  68. }
  69. // Set up variables for the watch mode ignore plugins
  70. const watched = {};
  71. const ignoreCache = Object.create(null);
  72. let watchNodeModules = false;
  73. Object.keys(jlab.linkedPackages).forEach(function (name) {
  74. if (name in watched) {
  75. return;
  76. }
  77. const localPkgPath = require.resolve(path.join(name, 'package.json'));
  78. watched[name] = path.dirname(localPkgPath);
  79. if (localPkgPath.indexOf('node_modules') !== -1) {
  80. watchNodeModules = true;
  81. }
  82. });
  83. // Set up source-map-loader to look in watched lib dirs
  84. const sourceMapRes = Object.values(watched).reduce((res, name) => {
  85. res.push(new RegExp(name + '/lib'));
  86. return res;
  87. }, []);
  88. /**
  89. * Sync a local path to a linked package path if they are files and differ.
  90. * This is used by `jupyter lab --watch` to synchronize linked packages
  91. * and has no effect in `jupyter lab --dev-mode --watch`.
  92. */
  93. function maybeSync(localPath, name, rest) {
  94. const stats = fs.statSync(localPath);
  95. if (!stats.isFile(localPath)) {
  96. return;
  97. }
  98. const source = fs.realpathSync(path.join(jlab.linkedPackages[name], rest));
  99. if (source === fs.realpathSync(localPath)) {
  100. return;
  101. }
  102. fs.watchFile(source, { interval: 500 }, function (curr) {
  103. if (!curr || curr.nlink === 0) {
  104. return;
  105. }
  106. try {
  107. fs.copySync(source, localPath);
  108. } catch (err) {
  109. console.error(err);
  110. }
  111. });
  112. }
  113. /**
  114. * A filter function set up to exclude all files that are not
  115. * in a package contained by the Jupyterlab repo. Used to ignore
  116. * files during a `--watch` build.
  117. */
  118. function ignored(path) {
  119. path = path.resolve(path);
  120. if (path in ignoreCache) {
  121. // Bail if already found.
  122. return ignoreCache[path];
  123. }
  124. // Limit the watched files to those in our local linked package dirs.
  125. let ignore = true;
  126. Object.keys(watched).some(name => {
  127. const rootPath = watched[name];
  128. const contained = path.indexOf(rootPath + path.sep) !== -1;
  129. if (path !== rootPath && !contained) {
  130. return false;
  131. }
  132. const rest = path.slice(rootPath.length);
  133. if (rest.indexOf('node_modules') === -1) {
  134. ignore = false;
  135. maybeSync(path, name, rest);
  136. }
  137. return true;
  138. });
  139. ignoreCache[path] = ignore;
  140. return ignore;
  141. }
  142. // Set up module federation sharing config
  143. const shared = {};
  144. // Make sure any resolutions are shared
  145. for (let [pkg, requiredVersion] of Object.entries(packageData.resolutions)) {
  146. shared[pkg] = { requiredVersion };
  147. }
  148. // Add any extension packages that are not in resolutions (i.e., installed from npm)
  149. for (let pkg of extensionPackages) {
  150. if (!shared[pkg]) {
  151. shared[pkg] = {
  152. requiredVersion: require(`${pkg}/package.json`).version
  153. };
  154. }
  155. }
  156. // Add dependencies and sharedPackage config from extension packages if they
  157. // are not already in the shared config. This means that if there is a
  158. // conflict, the resolutions package version is the one that is shared.
  159. const extraShared = [];
  160. for (let pkg of extensionPackages) {
  161. let pkgShared = {};
  162. let {
  163. dependencies = {},
  164. jupyterlab: { sharedPackages = {} } = {}
  165. } = require(`${pkg}/package.json`);
  166. for (let [dep, requiredVersion] of Object.entries(dependencies)) {
  167. if (!shared[dep]) {
  168. pkgShared[dep] = { requiredVersion };
  169. }
  170. }
  171. // Overwrite automatic dependency sharing with custom sharing config
  172. for (let [dep, config] of Object.entries(sharedPackages)) {
  173. if (config === false) {
  174. delete pkgShared[dep];
  175. } else {
  176. if ('bundled' in config) {
  177. config.import = config.bundled;
  178. delete config.bundled;
  179. }
  180. pkgShared[dep] = config;
  181. }
  182. }
  183. extraShared.push(pkgShared);
  184. }
  185. // Now merge the extra shared config
  186. const mergedShare = {};
  187. for (let sharedConfig of extraShared) {
  188. for (let [pkg, config] of Object.entries(sharedConfig)) {
  189. // Do not override the basic share config from resolutions
  190. if (shared[pkg]) {
  191. continue;
  192. }
  193. // Add if we haven't seen the config before
  194. if (!mergedShare[pkg]) {
  195. mergedShare[pkg] = config;
  196. continue;
  197. }
  198. // Choose between the existing config and this new config. We do not try
  199. // to merge configs, which may yield a config no one wants
  200. let oldConfig = mergedShare[pkg];
  201. // if the old one has import: false, use the new one
  202. if (oldConfig.import === false) {
  203. mergedShare[pkg] = config;
  204. }
  205. }
  206. }
  207. Object.assign(shared, mergedShare);
  208. // Transform any file:// requiredVersion to the version number from the
  209. // imported package. This assumes (for simplicity) that the version we get
  210. // importing was installed from the file.
  211. for (let [pkg, { requiredVersion }] of Object.entries(shared)) {
  212. if (requiredVersion && requiredVersion.startsWith('file:')) {
  213. shared[pkg].requiredVersion = require(`${pkg}/package.json`).version;
  214. }
  215. }
  216. // Add singleton package information
  217. for (let pkg of jlab.singletonPackages) {
  218. shared[pkg].singleton = true;
  219. }
  220. const plugins = [
  221. new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
  222. verbose: true,
  223. exclude(instance) {
  224. // ignore known duplicates
  225. return ['domelementtype', 'hash-base', 'inherits'].includes(
  226. instance.name
  227. );
  228. }
  229. }),
  230. new HtmlWebpackPlugin({
  231. chunksSortMode: 'none',
  232. template: path.join(__dirname, 'templates', 'template.html'),
  233. title: jlab.name || 'JupyterLab'
  234. }),
  235. // custom plugin for ignoring files during a `--watch` build
  236. new WPPlugin.FilterWatchIgnorePlugin(ignored),
  237. // custom plugin that copies the assets to the static directory
  238. new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  239. new ModuleFederationPlugin({
  240. library: {
  241. type: 'var',
  242. name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
  243. },
  244. name: 'CORE_FEDERATION',
  245. shared
  246. })
  247. ];
  248. if (process.argv.includes('--analyze')) {
  249. plugins.push(new BundleAnalyzerPlugin());
  250. }
  251. module.exports = [
  252. merge(baseConfig, {
  253. mode: 'development',
  254. entry: {
  255. main: ['./publicpath', 'whatwg-fetch', entryPoint]
  256. },
  257. output: {
  258. path: path.resolve(buildDir),
  259. publicPath: '{{page_config.fullStaticUrl}}/',
  260. filename: '[name].[contenthash].js'
  261. },
  262. optimization: {
  263. splitChunks: {
  264. chunks: 'all',
  265. cacheGroups: {
  266. jlab_core: {
  267. test: /[\\/]node_modules[\\/]@(jupyterlab|lumino)[\\/]/,
  268. name: 'jlab_core'
  269. }
  270. }
  271. }
  272. },
  273. module: {
  274. rules: [
  275. {
  276. test: /\.js$/,
  277. include: sourceMapRes,
  278. use: ['source-map-loader'],
  279. enforce: 'pre'
  280. }
  281. ]
  282. },
  283. devtool: 'inline-source-map',
  284. externals: ['node-fetch', 'ws'],
  285. plugins
  286. })
  287. ].concat(extensionAssetConfig);
  288. // Needed to watch changes in linked extensions in node_modules
  289. // (jupyter lab --watch)
  290. // See https://github.com/webpack/webpack/issues/11612
  291. if (watchNodeModules) {
  292. module.exports[0].snapshot = { managedPaths: [] };
  293. }
  294. const logPath = path.join(buildDir, 'build_log.json');
  295. fs.writeFileSync(logPath, JSON.stringify(module.exports, null, ' '));