webpack.config.js 12 KB

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