webpack.config.js 11 KB

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