webpack.config.js 12 KB

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