webpack.config.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. 'bootstrap-3': './frontend/js/bootstrap-3.ts',
  17. 'bootstrap-5': './frontend/js/bootstrap-5.ts',
  18. devToolbar: './frontend/js/dev-toolbar.ts',
  19. 'ide-detached': './frontend/js/ide-detached.ts',
  20. marketing: './frontend/js/marketing.ts',
  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. 'main-style-bootstrap-5':
  25. './frontend/stylesheets/bootstrap-5/main-style.scss',
  26. tracking: './frontend/js/infrastructure/tracking.ts',
  27. }
  28. // Add entrypoints for each "page"
  29. glob
  30. .sync(
  31. path.join(__dirname, 'modules/*/frontend/js/pages/**/*.{js,jsx,ts,tsx}')
  32. )
  33. .forEach(page => {
  34. // in: /workspace/services/web/modules/foo/frontend/js/pages/bar.js
  35. // out: modules/foo/pages/bar
  36. const name = path
  37. .relative(__dirname, page)
  38. .replace(/frontend[/]js[/]/, '')
  39. .replace(/.(js|jsx|ts|tsx)$/, '')
  40. entryPoints[name] = './' + path.relative(__dirname, page)
  41. })
  42. glob
  43. .sync(path.join(__dirname, 'frontend/js/pages/**/*.{js,jsx,ts,tsx}'))
  44. .forEach(page => {
  45. // in: /workspace/services/web/frontend/js/pages/marketing/homepage.js
  46. // out: pages/marketing/homepage
  47. const name = path
  48. .relative(path.join(__dirname, 'frontend/js/'), page)
  49. .replace(/.(js|jsx|ts|tsx)$/, '')
  50. entryPoints[name] = './' + path.relative(__dirname, page)
  51. })
  52. function getModuleDirectory(moduleName) {
  53. const entrypointPath = require.resolve(moduleName)
  54. const suffix = `node_modules/${moduleName}`
  55. const idx = entrypointPath.indexOf(suffix)
  56. if (idx === -1) {
  57. throw new Error(`could not find Node module: ${moduleName}`)
  58. }
  59. return entrypointPath.slice(0, idx + suffix.length)
  60. }
  61. const mathjaxDir = getModuleDirectory('mathjax')
  62. const pdfjsDir = getModuleDirectory('pdfjs-dist')
  63. const dictionariesDir = getModuleDirectory('@overleaf/dictionaries')
  64. const vendorDir = path.join(__dirname, 'frontend/js/vendor')
  65. const MATHJAX_VERSION = require('mathjax/package.json').version
  66. if (MATHJAX_VERSION !== PackageVersions.version.mathjax) {
  67. throw new Error(
  68. '"mathjax" version de-synced, update services/web/app/src/infrastructure/PackageVersions.js'
  69. )
  70. }
  71. const DICTIONARIES_VERSION =
  72. require('@overleaf/dictionaries/package.json').version
  73. if (DICTIONARIES_VERSION !== PackageVersions.version.dictionaries) {
  74. throw new Error(
  75. '"@overleaf/dictionaries" version de-synced, update services/web/app/src/infrastructure/PackageVersions.js'
  76. )
  77. }
  78. module.exports = {
  79. // Defines the "entry point(s)" for the application - i.e. the file which
  80. // bootstraps the application
  81. entry: entryPoints,
  82. // Define where and how the bundle will be output to disk
  83. // Note: webpack-dev-server does not write the bundle to disk, instead it is
  84. // kept in memory for speed
  85. output: {
  86. path: path.join(__dirname, 'public'),
  87. publicPath: '/',
  88. workerPublicPath: '/',
  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. // https://webpack.js.org/configuration/optimization/#optimizationruntimechunk
  103. runtimeChunk: {
  104. name: 'runtime',
  105. },
  106. },
  107. // Define how file types are handled by webpack
  108. module: {
  109. rules: [
  110. {
  111. // Pass application JS/TS files through babel-loader,
  112. // transpiling to targets defined in browserslist
  113. test: /\.([jt]sx?|[cm]js)$/,
  114. // Only compile application files and specific dependencies
  115. // (other npm and vendored dependencies must be in ES5 already)
  116. exclude: [
  117. /node_modules\/(?!(react-dnd|chart\.js|@uppy|pdfjs-dist|react-resizable-panels)\/)/,
  118. vendorDir,
  119. ],
  120. use: [
  121. {
  122. loader: 'babel-loader',
  123. options: {
  124. // Configure babel-loader to cache compiled output so that
  125. // subsequent compile runs are much faster
  126. cacheDirectory: true,
  127. configFile: path.join(__dirname, './babel.config.json'),
  128. plugins: [
  129. process.env.REACT_REFRESH_ENABLED === 'true' &&
  130. 'react-refresh/babel',
  131. ].filter(Boolean),
  132. },
  133. },
  134. ],
  135. type: 'javascript/auto',
  136. },
  137. {
  138. test: /\.wasm$/,
  139. type: 'asset/resource',
  140. generator: {
  141. filename: 'js/[name]-[contenthash][ext]',
  142. },
  143. },
  144. {
  145. test: /\.txt$/,
  146. type: 'asset/source',
  147. generator: {
  148. filename: 'js/[name]-[contenthash][ext]',
  149. },
  150. },
  151. {
  152. // Pass Less files through less-loader/css-loader/mini-css-extract-
  153. // plugin (note: run in reverse order)
  154. test: /\.less$/,
  155. use: [
  156. // Allows the CSS to be extracted to a separate .css file
  157. { loader: MiniCssExtractPlugin.loader },
  158. // Resolves any CSS dependencies (e.g. url())
  159. { loader: 'css-loader' },
  160. {
  161. // Runs autoprefixer on CSS via postcss
  162. loader: 'postcss-loader',
  163. options: {
  164. postcssOptions: {
  165. plugins: ['autoprefixer'],
  166. },
  167. },
  168. },
  169. // Compile Less off the main event loop
  170. {
  171. loader: 'thread-loader',
  172. options: {
  173. // keep workers alive for dev-server, and shut them down when not needed
  174. poolTimeout:
  175. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  176. // bring up more workers after they timed out
  177. poolRespawn: true,
  178. // limit concurrency (one per entrypoint and let the small includes queue up)
  179. workers: process.env.NODE_ENV === 'test' ? 1 : 6,
  180. },
  181. },
  182. // Compiles the Less syntax to CSS
  183. { loader: 'less-loader' },
  184. ],
  185. },
  186. {
  187. // Pass Sass files through sass-loader/css-loader/mini-css-extract-
  188. // plugin (note: run in reverse order)
  189. test: /\.s[ac]ss$/,
  190. use: [
  191. // Allows the CSS to be extracted to a separate .css file
  192. { loader: MiniCssExtractPlugin.loader },
  193. // Resolves any CSS dependencies (e.g. url())
  194. { loader: 'css-loader' },
  195. // Resolve relative paths sensibly in SASS
  196. { loader: 'resolve-url-loader' },
  197. {
  198. // Runs autoprefixer on CSS via postcss
  199. loader: 'postcss-loader',
  200. options: {
  201. postcssOptions: {
  202. plugins: ['autoprefixer'],
  203. },
  204. },
  205. },
  206. // Compile Sass off the main event loop
  207. {
  208. loader: 'thread-loader',
  209. options: {
  210. // keep workers alive for dev-server, and shut them down when not needed
  211. poolTimeout:
  212. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  213. // bring up more workers after they timed out
  214. poolRespawn: true,
  215. // limit concurrency (one per entrypoint and let the small includes queue up)
  216. workers: 6,
  217. },
  218. },
  219. // Compiles Sass to CSS
  220. {
  221. loader: 'sass-loader',
  222. options: { sourceMap: true }, // sourceMap: true is required for resolve-url-loader
  223. },
  224. ],
  225. },
  226. {
  227. // Pass CSS files through css-loader & mini-css-extract-plugin (note: run in reverse order)
  228. test: /\.css$/i,
  229. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  230. },
  231. {
  232. // Load fonts
  233. test: /\.(woff2?|ttf|otf)$/,
  234. type: 'asset/resource',
  235. generator: {
  236. filename: 'fonts/[name]-[contenthash][ext]',
  237. },
  238. },
  239. {
  240. // Load images and videos (static files)
  241. test: /\.(svg|gif|png|jpg|pdf|mp4)$/,
  242. type: 'asset/resource',
  243. generator: {
  244. filename: 'images/[name]-[contenthash][ext]',
  245. },
  246. },
  247. {
  248. // These options are necessary for handlebars to have access to helper
  249. // methods
  250. test: /\.handlebars$/,
  251. loader: 'handlebars-loader',
  252. options: {
  253. compat: true,
  254. knownHelpersOnly: false,
  255. runtimePath: 'handlebars/runtime',
  256. },
  257. },
  258. {
  259. // Load translations files with custom loader, to extract and apply
  260. // fallbacks
  261. test: /locales\/(\w{2}(-\w{2})?)\.json$/,
  262. use: [
  263. {
  264. loader: path.join(__dirname, 'frontend/translations-loader.js'),
  265. },
  266. ],
  267. },
  268. ],
  269. },
  270. resolve: {
  271. alias: {
  272. // custom prefixes for import paths
  273. '@': path.resolve(__dirname, './frontend/js/'),
  274. '@ol-types': path.resolve(__dirname, './types/'),
  275. },
  276. // symlinks: false, // enable this while using `npm link`
  277. extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'],
  278. fallback: {
  279. events: require.resolve('events'),
  280. // for react-dnd + React 17
  281. 'react/jsx-runtime': 'react/jsx-runtime.js',
  282. 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js',
  283. },
  284. },
  285. experiments: {
  286. asyncWebAssembly: true,
  287. },
  288. plugins: [
  289. new LezerGrammarCompilerPlugin(),
  290. // Generate a manifest.json file which is used by the backend to map the
  291. // base filenames to the generated output filenames
  292. new WebpackAssetsManifest({
  293. entrypoints: true,
  294. publicPath: true,
  295. output: 'manifest.json',
  296. }),
  297. new webpack.EnvironmentPlugin({
  298. // Ensure that process.env.RESET_APP_DATA_TIMER is defined, to avoid an error.
  299. // https://github.com/algolia/algoliasearch-client-javascript/issues/756
  300. RESET_APP_DATA_TIMER: '120000',
  301. // Ensure that process.env.CYPRESS is defined (see utils/worker.js)
  302. CYPRESS: false,
  303. }),
  304. // Prevent moment from loading (very large) locale files that aren't used
  305. new webpack.IgnorePlugin({
  306. resourceRegExp: /^\.\/locale$/,
  307. contextRegExp: /moment$/,
  308. }),
  309. // Set window.$ and window.jQuery
  310. new webpack.ProvidePlugin({
  311. $: 'jquery',
  312. jQuery: 'jquery',
  313. }),
  314. new CopyPlugin({
  315. patterns: [
  316. // Copy the required files for loading MathJax from MathJax NPM package
  317. // https://www.npmjs.com/package/mathjax#user-content-hosting-your-own-copy-of-the-mathjax-components
  318. {
  319. from: 'es5/tex-svg-full.js',
  320. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5`,
  321. toType: 'dir',
  322. context: mathjaxDir,
  323. },
  324. {
  325. from: 'es5/input/tex/extensions/**/*.js',
  326. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  327. toType: 'dir',
  328. context: mathjaxDir,
  329. },
  330. {
  331. from: 'es5/ui/**/*',
  332. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  333. toType: 'dir',
  334. context: mathjaxDir,
  335. },
  336. {
  337. from: 'es5/a11y/**/*',
  338. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  339. toType: 'dir',
  340. context: mathjaxDir,
  341. },
  342. {
  343. from: 'es5/input/mml.js',
  344. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5/input`,
  345. toType: 'dir',
  346. context: mathjaxDir,
  347. },
  348. {
  349. from: 'es5/sre/**/*',
  350. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  351. toType: 'dir',
  352. context: mathjaxDir,
  353. },
  354. {
  355. from: '*',
  356. to: `js/dictionaries/${PackageVersions.version.dictionaries}`,
  357. toType: 'dir',
  358. context: `${dictionariesDir}/dictionaries`,
  359. },
  360. // Copy CMap files (used to provide support for non-Latin characters),
  361. // wasm, ICC profiles, fonts and images from pdfjs-dist package to build output.
  362. {
  363. from: 'cmaps',
  364. to: 'js/pdfjs-dist/cmaps',
  365. context: pdfjsDir,
  366. },
  367. {
  368. from: 'iccs',
  369. to: 'js/pdfjs-dist/iccs',
  370. context: pdfjsDir,
  371. },
  372. {
  373. from: 'wasm',
  374. to: 'js/pdfjs-dist/wasm',
  375. context: pdfjsDir,
  376. },
  377. {
  378. from: 'standard_fonts',
  379. to: 'fonts/pdfjs-dist',
  380. context: pdfjsDir,
  381. },
  382. {
  383. from: 'legacy/web/images',
  384. to: 'images/pdfjs-dist',
  385. context: pdfjsDir,
  386. },
  387. ],
  388. }),
  389. ],
  390. }