webpack.config.js 11 KB

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