webpack.config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. const path = require('path')
  2. const glob = require('glob')
  3. const webpack = require('webpack')
  4. const CopyPlugin = require('copy-webpack-plugin')
  5. const WebpackAssetsManifest = require('webpack-assets-manifest')
  6. const MiniCssExtractPlugin = require('mini-css-extract-plugin')
  7. const {
  8. LezerGrammarCompilerPlugin,
  9. } = require('./webpack-plugins/lezer-grammar-compiler')
  10. const PackageVersions = require('./app/src/infrastructure/PackageVersions')
  11. const invalidateBabelCacheIfNeeded = require('./frontend/macros/invalidate-babel-cache-if-needed')
  12. // Make sure that babel-macros are re-evaluated after changing the modules config
  13. invalidateBabelCacheIfNeeded()
  14. // Generate a hash of entry points, including modules
  15. const entryPoints = {
  16. tracing: './frontend/js/tracing.js',
  17. 'bootstrap-3': './frontend/js/bootstrap-3.ts',
  18. 'bootstrap-5': './frontend/js/bootstrap-5.ts',
  19. devToolbar: './frontend/js/dev-toolbar.js',
  20. 'ide-detached': './frontend/js/ide-detached.js',
  21. marketing: './frontend/js/marketing.js',
  22. 'main-style': './frontend/stylesheets/main-style.less',
  23. 'main-ieee-style': './frontend/stylesheets/main-ieee-style.less',
  24. 'main-light-style': './frontend/stylesheets/main-light-style.less',
  25. 'main-style-bootstrap-5':
  26. './frontend/stylesheets/bootstrap-5/main-style.scss',
  27. 'main-ieee-style-bootstrap-5':
  28. './frontend/stylesheets/bootstrap-5/main-ieee-style.scss',
  29. 'main-light-style-bootstrap-5':
  30. './frontend/stylesheets/bootstrap-5/main-light-style.scss',
  31. }
  32. // Add entrypoints for each "page"
  33. glob
  34. .sync(
  35. path.join(__dirname, 'modules/*/frontend/js/pages/**/*.{js,jsx,ts,tsx}')
  36. )
  37. .forEach(page => {
  38. // in: /workspace/services/web/modules/foo/frontend/js/pages/bar.js
  39. // out: modules/foo/pages/bar
  40. const name = path
  41. .relative(__dirname, page)
  42. .replace(/frontend[/]js[/]/, '')
  43. .replace(/.(js|jsx|ts|tsx)$/, '')
  44. entryPoints[name] = './' + path.relative(__dirname, page)
  45. })
  46. glob
  47. .sync(path.join(__dirname, 'frontend/js/pages/**/*.{js,jsx,ts,tsx}'))
  48. .forEach(page => {
  49. // in: /workspace/services/web/frontend/js/pages/marketing/homepage.js
  50. // out: pages/marketing/homepage
  51. const name = path
  52. .relative(path.join(__dirname, 'frontend/js/'), page)
  53. .replace(/.(js|jsx|ts|tsx)$/, '')
  54. entryPoints[name] = './' + path.relative(__dirname, page)
  55. })
  56. function getModuleDirectory(moduleName) {
  57. const entrypointPath = require.resolve(moduleName)
  58. const suffix = `node_modules/${moduleName}`
  59. const idx = entrypointPath.indexOf(suffix)
  60. if (idx === -1) {
  61. throw new Error(`could not find Node module: ${moduleName}`)
  62. }
  63. return entrypointPath.slice(0, idx + suffix.length)
  64. }
  65. const mathjaxDir = getModuleDirectory('mathjax')
  66. const pdfjsVersions = ['pdfjs-dist213', 'pdfjs-dist401']
  67. const vendorDir = path.join(__dirname, 'frontend/js/vendor')
  68. const MATHJAX_VERSION = require('mathjax/package.json').version
  69. if (MATHJAX_VERSION !== PackageVersions.version.mathjax) {
  70. throw new Error(
  71. '"mathjax" version de-synced, update services/web/app/src/infrastructure/PackageVersions.js'
  72. )
  73. }
  74. module.exports = {
  75. // Defines the "entry point(s)" for the application - i.e. the file which
  76. // bootstraps the application
  77. entry: entryPoints,
  78. // Define where and how the bundle will be output to disk
  79. // Note: webpack-dev-server does not write the bundle to disk, instead it is
  80. // kept in memory for speed
  81. output: {
  82. path: path.join(__dirname, 'public'),
  83. publicPath: '/',
  84. // By default write into js directory
  85. filename: 'js/[name]-[contenthash].js',
  86. // Output as UMD bundle (allows main JS to import with CJS, AMD or global
  87. // style code bundles
  88. libraryTarget: 'umd',
  89. // Name the exported variable from output bundle
  90. library: ['Frontend', '[name]'],
  91. },
  92. optimization: {
  93. // https://webpack.js.org/plugins/split-chunks-plugin/#splitchunkschunks
  94. splitChunks: {
  95. chunks: 'all', // allow non-async chunks to be analysed for shared modules
  96. },
  97. },
  98. // Define how file types are handled by webpack
  99. module: {
  100. rules: [
  101. {
  102. // Pass application JS/TS files through babel-loader,
  103. // transpiling to targets defined in browserslist
  104. test: /\.([jt]sx?|[cm]js)$/,
  105. // Only compile application files and specific dependencies
  106. // (other npm and vendored dependencies must be in ES5 already)
  107. exclude: [/node_modules\/(?!(react-dnd|chart\.js|@uppy)\/)/, vendorDir],
  108. use: [
  109. {
  110. loader: 'babel-loader',
  111. options: {
  112. // Configure babel-loader to cache compiled output so that
  113. // subsequent compile runs are much faster
  114. cacheDirectory: true,
  115. configFile: path.join(__dirname, './babel.config.json'),
  116. plugins: [
  117. process.env.REACT_REFRESH && 'react-refresh/babel',
  118. ].filter(Boolean),
  119. },
  120. },
  121. ],
  122. type: 'javascript/auto',
  123. },
  124. {
  125. // Pass Less files through less-loader/css-loader/mini-css-extract-
  126. // plugin (note: run in reverse order)
  127. test: /\.less$/,
  128. use: [
  129. // Allows the CSS to be extracted to a separate .css file
  130. { loader: MiniCssExtractPlugin.loader },
  131. // Resolves any CSS dependencies (e.g. url())
  132. { loader: 'css-loader' },
  133. {
  134. // Runs autoprefixer on CSS via postcss
  135. loader: 'postcss-loader',
  136. options: {
  137. postcssOptions: {
  138. plugins: ['autoprefixer'],
  139. },
  140. },
  141. },
  142. // Compile Less off the main event loop
  143. {
  144. loader: 'thread-loader',
  145. options: {
  146. // keep workers alive for dev-server, and shut them down when not needed
  147. poolTimeout:
  148. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  149. // bring up more workers after they timed out
  150. poolRespawn: true,
  151. // limit concurrency (one per entrypoint and let the small includes queue up)
  152. workers: 6,
  153. },
  154. },
  155. // Compiles the Less syntax to CSS
  156. { loader: 'less-loader' },
  157. ],
  158. },
  159. {
  160. // Pass Sass files through sass-loader/css-loader/mini-css-extract-
  161. // plugin (note: run in reverse order)
  162. test: /\.s[ac]ss$/,
  163. use: [
  164. // Allows the CSS to be extracted to a separate .css file
  165. { loader: MiniCssExtractPlugin.loader },
  166. // Resolves any CSS dependencies (e.g. url())
  167. { loader: 'css-loader' },
  168. // Resolve relative paths sensibly in SASS
  169. { loader: 'resolve-url-loader' },
  170. {
  171. // Runs autoprefixer on CSS via postcss
  172. loader: 'postcss-loader',
  173. options: {
  174. postcssOptions: {
  175. plugins: ['autoprefixer'],
  176. },
  177. },
  178. },
  179. // Compile Sass off the main event loop
  180. {
  181. loader: 'thread-loader',
  182. options: {
  183. // keep workers alive for dev-server, and shut them down when not needed
  184. poolTimeout:
  185. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  186. // bring up more workers after they timed out
  187. poolRespawn: true,
  188. // limit concurrency (one per entrypoint and let the small includes queue up)
  189. workers: 6,
  190. },
  191. },
  192. // Compiles Sass to CSS
  193. {
  194. loader: 'sass-loader',
  195. options: { sourceMap: true }, // sourceMap: true is required for resolve-url-loader
  196. },
  197. ],
  198. },
  199. {
  200. // Pass CSS files through css-loader & mini-css-extract-plugin (note: run in reverse order)
  201. test: /\.css$/i,
  202. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  203. },
  204. {
  205. // Load fonts
  206. test: /\.(woff2?|ttf|otf)$/,
  207. type: 'asset/resource',
  208. generator: {
  209. filename: 'fonts/[name]-[contenthash][ext]',
  210. },
  211. },
  212. {
  213. // Load images (static files)
  214. test: /\.(svg|gif|png|jpg|pdf)$/,
  215. type: 'asset/resource',
  216. generator: {
  217. filename: 'images/[name]-[contenthash][ext]',
  218. },
  219. },
  220. {
  221. // These options are necessary for handlebars to have access to helper
  222. // methods
  223. test: /\.handlebars$/,
  224. loader: 'handlebars-loader',
  225. options: {
  226. compat: true,
  227. knownHelpersOnly: false,
  228. runtimePath: 'handlebars/runtime',
  229. },
  230. },
  231. {
  232. // Load translations files with custom loader, to extract and apply
  233. // fallbacks
  234. test: /locales\/(\w{2}(-\w{2})?)\.json$/,
  235. use: [
  236. {
  237. loader: path.join(__dirname, 'frontend/translations-loader.js'),
  238. },
  239. ],
  240. },
  241. ],
  242. },
  243. resolve: {
  244. alias: {
  245. // custom prefixes for import paths
  246. '@': path.resolve(__dirname, './frontend/js/'),
  247. },
  248. // symlinks: false, // enable this while using `npm link`
  249. extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'],
  250. fallback: {
  251. events: require.resolve('events'),
  252. // for react-dnd + React 17
  253. 'react/jsx-runtime': 'react/jsx-runtime.js',
  254. 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js',
  255. },
  256. },
  257. plugins: [
  258. new LezerGrammarCompilerPlugin(),
  259. // Generate a manifest.json file which is used by the backend to map the
  260. // base filenames to the generated output filenames
  261. new WebpackAssetsManifest({
  262. entrypoints: true,
  263. publicPath: true,
  264. output: 'manifest.json',
  265. }),
  266. new webpack.EnvironmentPlugin({
  267. // Ensure that process.env.RESET_APP_DATA_TIMER is defined, to avoid an error.
  268. // https://github.com/algolia/algoliasearch-client-javascript/issues/756
  269. RESET_APP_DATA_TIMER: '120000',
  270. // Ensure that process.env.CYPRESS is defined (see utils/worker.js)
  271. CYPRESS: false,
  272. }),
  273. // Prevent moment from loading (very large) locale files that aren't used
  274. new webpack.IgnorePlugin({
  275. resourceRegExp: /^\.\/locale$/,
  276. contextRegExp: /moment$/,
  277. }),
  278. // Set window.$ and window.jQuery
  279. new webpack.ProvidePlugin({
  280. $: 'jquery',
  281. jQuery: 'jquery',
  282. }),
  283. // Copy the required files for loading MathJax from MathJax NPM package
  284. new CopyPlugin({
  285. patterns: [
  286. // https://www.npmjs.com/package/mathjax#user-content-hosting-your-own-copy-of-the-mathjax-components
  287. {
  288. from: 'es5/tex-svg-full.js',
  289. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5`,
  290. toType: 'dir',
  291. context: mathjaxDir,
  292. },
  293. {
  294. from: 'es5/input/tex/extensions/**/*.js',
  295. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  296. toType: 'dir',
  297. context: mathjaxDir,
  298. },
  299. {
  300. from: 'es5/ui/**/*',
  301. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  302. toType: 'dir',
  303. context: mathjaxDir,
  304. },
  305. {
  306. from: 'es5/a11y/**/*',
  307. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  308. toType: 'dir',
  309. context: mathjaxDir,
  310. },
  311. {
  312. from: 'es5/input/mml.js',
  313. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5/input`,
  314. toType: 'dir',
  315. context: mathjaxDir,
  316. },
  317. {
  318. from: 'es5/sre/**/*',
  319. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  320. toType: 'dir',
  321. context: mathjaxDir,
  322. },
  323. ...pdfjsVersions.flatMap(version => {
  324. const dir = getModuleDirectory(version)
  325. // Copy CMap files (used to provide support for non-Latin characters)
  326. // and static images from pdfjs-dist package to build output.
  327. return [
  328. { from: `cmaps`, to: `js/${version}/cmaps`, context: dir },
  329. {
  330. from: `standard_fonts`,
  331. to: `fonts/${version}`,
  332. context: dir,
  333. },
  334. {
  335. from: `legacy/web/images`,
  336. to: `images/${version}`,
  337. context: dir,
  338. },
  339. ]
  340. }),
  341. ],
  342. }),
  343. ],
  344. }