webpack.config.js 11 KB

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