webpack.config.js 12 KB

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