webpack.config.js 12 KB

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