webpack.config.js 9.8 KB

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