webpack.config.js 12 KB

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