webpack.config.js 12 KB

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