webpack.config.js 10 KB

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