webpack.config.js 12 KB

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