webpack.config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. // https://webpack.js.org/configuration/optimization/#optimizationruntimechunk
  98. runtimeChunk: {
  99. name: 'runtime',
  100. },
  101. },
  102. // Define how file types are handled by webpack
  103. module: {
  104. rules: [
  105. {
  106. // Pass application JS/TS files through babel-loader,
  107. // transpiling to targets defined in browserslist
  108. test: /\.([jt]sx?|[cm]js)$/,
  109. // Only compile application files and specific dependencies
  110. // (other npm and vendored dependencies must be in ES5 already)
  111. exclude: [/node_modules\/(?!(react-dnd|chart\.js|@uppy)\/)/, vendorDir],
  112. use: [
  113. {
  114. loader: 'babel-loader',
  115. options: {
  116. // Configure babel-loader to cache compiled output so that
  117. // subsequent compile runs are much faster
  118. cacheDirectory: true,
  119. configFile: path.join(__dirname, './babel.config.json'),
  120. plugins: [
  121. process.env.REACT_REFRESH && 'react-refresh/babel',
  122. ].filter(Boolean),
  123. },
  124. },
  125. ],
  126. type: 'javascript/auto',
  127. },
  128. {
  129. // Pass Less files through less-loader/css-loader/mini-css-extract-
  130. // plugin (note: run in reverse order)
  131. test: /\.less$/,
  132. use: [
  133. // Allows the CSS to be extracted to a separate .css file
  134. { loader: MiniCssExtractPlugin.loader },
  135. // Resolves any CSS dependencies (e.g. url())
  136. { loader: 'css-loader' },
  137. {
  138. // Runs autoprefixer on CSS via postcss
  139. loader: 'postcss-loader',
  140. options: {
  141. postcssOptions: {
  142. plugins: ['autoprefixer'],
  143. },
  144. },
  145. },
  146. // Compile Less off the main event loop
  147. {
  148. loader: 'thread-loader',
  149. options: {
  150. // keep workers alive for dev-server, and shut them down when not needed
  151. poolTimeout:
  152. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  153. // bring up more workers after they timed out
  154. poolRespawn: true,
  155. // limit concurrency (one per entrypoint and let the small includes queue up)
  156. workers: 6,
  157. },
  158. },
  159. // Compiles the Less syntax to CSS
  160. { loader: 'less-loader' },
  161. ],
  162. },
  163. {
  164. // Pass Sass files through sass-loader/css-loader/mini-css-extract-
  165. // plugin (note: run in reverse order)
  166. test: /\.s[ac]ss$/,
  167. use: [
  168. // Allows the CSS to be extracted to a separate .css file
  169. { loader: MiniCssExtractPlugin.loader },
  170. // Resolves any CSS dependencies (e.g. url())
  171. { loader: 'css-loader' },
  172. // Resolve relative paths sensibly in SASS
  173. { loader: 'resolve-url-loader' },
  174. {
  175. // Runs autoprefixer on CSS via postcss
  176. loader: 'postcss-loader',
  177. options: {
  178. postcssOptions: {
  179. plugins: ['autoprefixer'],
  180. },
  181. },
  182. },
  183. // Compile Sass off the main event loop
  184. {
  185. loader: 'thread-loader',
  186. options: {
  187. // keep workers alive for dev-server, and shut them down when not needed
  188. poolTimeout:
  189. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  190. // bring up more workers after they timed out
  191. poolRespawn: true,
  192. // limit concurrency (one per entrypoint and let the small includes queue up)
  193. workers: 6,
  194. },
  195. },
  196. // Compiles Sass to CSS
  197. {
  198. loader: 'sass-loader',
  199. options: { sourceMap: true }, // sourceMap: true is required for resolve-url-loader
  200. },
  201. ],
  202. },
  203. {
  204. // Pass CSS files through css-loader & mini-css-extract-plugin (note: run in reverse order)
  205. test: /\.css$/i,
  206. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  207. },
  208. {
  209. // Load fonts
  210. test: /\.(woff2?|ttf|otf)$/,
  211. type: 'asset/resource',
  212. generator: {
  213. filename: 'fonts/[name]-[contenthash][ext]',
  214. },
  215. },
  216. {
  217. // Load images (static files)
  218. test: /\.(svg|gif|png|jpg|pdf)$/,
  219. type: 'asset/resource',
  220. generator: {
  221. filename: 'images/[name]-[contenthash][ext]',
  222. },
  223. },
  224. {
  225. // These options are necessary for handlebars to have access to helper
  226. // methods
  227. test: /\.handlebars$/,
  228. loader: 'handlebars-loader',
  229. options: {
  230. compat: true,
  231. knownHelpersOnly: false,
  232. runtimePath: 'handlebars/runtime',
  233. },
  234. },
  235. {
  236. // Load translations files with custom loader, to extract and apply
  237. // fallbacks
  238. test: /locales\/(\w{2}(-\w{2})?)\.json$/,
  239. use: [
  240. {
  241. loader: path.join(__dirname, 'frontend/translations-loader.js'),
  242. },
  243. ],
  244. },
  245. ],
  246. },
  247. resolve: {
  248. alias: {
  249. // custom prefixes for import paths
  250. '@': path.resolve(__dirname, './frontend/js/'),
  251. },
  252. // symlinks: false, // enable this while using `npm link`
  253. extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'],
  254. fallback: {
  255. events: require.resolve('events'),
  256. // for react-dnd + React 17
  257. 'react/jsx-runtime': 'react/jsx-runtime.js',
  258. 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js',
  259. },
  260. },
  261. plugins: [
  262. new LezerGrammarCompilerPlugin(),
  263. // Generate a manifest.json file which is used by the backend to map the
  264. // base filenames to the generated output filenames
  265. new WebpackAssetsManifest({
  266. entrypoints: true,
  267. publicPath: true,
  268. output: 'manifest.json',
  269. }),
  270. new webpack.EnvironmentPlugin({
  271. // Ensure that process.env.RESET_APP_DATA_TIMER is defined, to avoid an error.
  272. // https://github.com/algolia/algoliasearch-client-javascript/issues/756
  273. RESET_APP_DATA_TIMER: '120000',
  274. // Ensure that process.env.CYPRESS is defined (see utils/worker.js)
  275. CYPRESS: false,
  276. }),
  277. // Prevent moment from loading (very large) locale files that aren't used
  278. new webpack.IgnorePlugin({
  279. resourceRegExp: /^\.\/locale$/,
  280. contextRegExp: /moment$/,
  281. }),
  282. // Set window.$ and window.jQuery
  283. new webpack.ProvidePlugin({
  284. $: 'jquery',
  285. jQuery: 'jquery',
  286. }),
  287. // Copy the required files for loading MathJax from MathJax NPM package
  288. new CopyPlugin({
  289. patterns: [
  290. // https://www.npmjs.com/package/mathjax#user-content-hosting-your-own-copy-of-the-mathjax-components
  291. {
  292. from: 'es5/tex-svg-full.js',
  293. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5`,
  294. toType: 'dir',
  295. context: mathjaxDir,
  296. },
  297. {
  298. from: 'es5/input/tex/extensions/**/*.js',
  299. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  300. toType: 'dir',
  301. context: mathjaxDir,
  302. },
  303. {
  304. from: 'es5/ui/**/*',
  305. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  306. toType: 'dir',
  307. context: mathjaxDir,
  308. },
  309. {
  310. from: 'es5/a11y/**/*',
  311. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  312. toType: 'dir',
  313. context: mathjaxDir,
  314. },
  315. {
  316. from: 'es5/input/mml.js',
  317. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5/input`,
  318. toType: 'dir',
  319. context: mathjaxDir,
  320. },
  321. {
  322. from: 'es5/sre/**/*',
  323. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  324. toType: 'dir',
  325. context: mathjaxDir,
  326. },
  327. ...pdfjsVersions.flatMap(version => {
  328. const dir = getModuleDirectory(version)
  329. // Copy CMap files (used to provide support for non-Latin characters)
  330. // and static images from pdfjs-dist package to build output.
  331. return [
  332. { from: `cmaps`, to: `js/${version}/cmaps`, context: dir },
  333. {
  334. from: `standard_fonts`,
  335. to: `fonts/${version}`,
  336. context: dir,
  337. },
  338. {
  339. from: `legacy/web/images`,
  340. to: `images/${version}`,
  341. context: dir,
  342. },
  343. ]
  344. }),
  345. ],
  346. }),
  347. ],
  348. }