webpack.config.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. tracing: './frontend/js/tracing.js',
  17. 'bootstrap-3': './frontend/js/bootstrap-3.ts',
  18. 'bootstrap-5': './frontend/js/bootstrap-5.ts',
  19. devToolbar: './frontend/js/dev-toolbar.ts',
  20. 'ide-detached': './frontend/js/ide-detached.ts',
  21. marketing: './frontend/js/marketing.ts',
  22. 'main-style': './frontend/stylesheets/main-style.less',
  23. 'main-ieee-style': './frontend/stylesheets/main-ieee-style.less',
  24. 'main-light-style': './frontend/stylesheets/main-light-style.less',
  25. 'main-style-bootstrap-5':
  26. './frontend/stylesheets/bootstrap-5/main-style.scss',
  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. // Pass Less files through less-loader/css-loader/mini-css-extract-
  146. // plugin (note: run in reverse order)
  147. test: /\.less$/,
  148. use: [
  149. // Allows the CSS to be extracted to a separate .css file
  150. { loader: MiniCssExtractPlugin.loader },
  151. // Resolves any CSS dependencies (e.g. url())
  152. { loader: 'css-loader' },
  153. {
  154. // Runs autoprefixer on CSS via postcss
  155. loader: 'postcss-loader',
  156. options: {
  157. postcssOptions: {
  158. plugins: ['autoprefixer'],
  159. },
  160. },
  161. },
  162. // Compile Less off the main event loop
  163. {
  164. loader: 'thread-loader',
  165. options: {
  166. // keep workers alive for dev-server, and shut them down when not needed
  167. poolTimeout:
  168. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  169. // bring up more workers after they timed out
  170. poolRespawn: true,
  171. // limit concurrency (one per entrypoint and let the small includes queue up)
  172. workers: process.env.NODE_ENV === 'test' ? 1 : 6,
  173. },
  174. },
  175. // Compiles the Less syntax to CSS
  176. { loader: 'less-loader' },
  177. ],
  178. },
  179. {
  180. // Pass Sass files through sass-loader/css-loader/mini-css-extract-
  181. // plugin (note: run in reverse order)
  182. test: /\.s[ac]ss$/,
  183. use: [
  184. // Allows the CSS to be extracted to a separate .css file
  185. { loader: MiniCssExtractPlugin.loader },
  186. // Resolves any CSS dependencies (e.g. url())
  187. { loader: 'css-loader' },
  188. // Resolve relative paths sensibly in SASS
  189. { loader: 'resolve-url-loader' },
  190. {
  191. // Runs autoprefixer on CSS via postcss
  192. loader: 'postcss-loader',
  193. options: {
  194. postcssOptions: {
  195. plugins: ['autoprefixer'],
  196. },
  197. },
  198. },
  199. // Compile Sass off the main event loop
  200. {
  201. loader: 'thread-loader',
  202. options: {
  203. // keep workers alive for dev-server, and shut them down when not needed
  204. poolTimeout:
  205. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  206. // bring up more workers after they timed out
  207. poolRespawn: true,
  208. // limit concurrency (one per entrypoint and let the small includes queue up)
  209. workers: 6,
  210. },
  211. },
  212. // Compiles Sass to CSS
  213. {
  214. loader: 'sass-loader',
  215. options: { sourceMap: true }, // sourceMap: true is required for resolve-url-loader
  216. },
  217. ],
  218. },
  219. {
  220. // Pass CSS files through css-loader & mini-css-extract-plugin (note: run in reverse order)
  221. test: /\.css$/i,
  222. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  223. },
  224. {
  225. // Load fonts
  226. test: /\.(woff2?|ttf|otf)$/,
  227. type: 'asset/resource',
  228. generator: {
  229. filename: 'fonts/[name]-[contenthash][ext]',
  230. },
  231. },
  232. {
  233. // Load images and videos (static files)
  234. test: /\.(svg|gif|png|jpg|pdf|mp4)$/,
  235. type: 'asset/resource',
  236. generator: {
  237. filename: 'images/[name]-[contenthash][ext]',
  238. },
  239. },
  240. {
  241. // These options are necessary for handlebars to have access to helper
  242. // methods
  243. test: /\.handlebars$/,
  244. loader: 'handlebars-loader',
  245. options: {
  246. compat: true,
  247. knownHelpersOnly: false,
  248. runtimePath: 'handlebars/runtime',
  249. },
  250. },
  251. {
  252. // Load translations files with custom loader, to extract and apply
  253. // fallbacks
  254. test: /locales\/(\w{2}(-\w{2})?)\.json$/,
  255. use: [
  256. {
  257. loader: path.join(__dirname, 'frontend/translations-loader.js'),
  258. },
  259. ],
  260. },
  261. ],
  262. },
  263. resolve: {
  264. alias: {
  265. // custom prefixes for import paths
  266. '@': path.resolve(__dirname, './frontend/js/'),
  267. },
  268. // symlinks: false, // enable this while using `npm link`
  269. extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'],
  270. fallback: {
  271. events: require.resolve('events'),
  272. // for react-dnd + React 17
  273. 'react/jsx-runtime': 'react/jsx-runtime.js',
  274. 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js',
  275. },
  276. },
  277. experiments: {
  278. asyncWebAssembly: true,
  279. },
  280. plugins: [
  281. new LezerGrammarCompilerPlugin(),
  282. // Generate a manifest.json file which is used by the backend to map the
  283. // base filenames to the generated output filenames
  284. new WebpackAssetsManifest({
  285. entrypoints: true,
  286. publicPath: true,
  287. output: 'manifest.json',
  288. }),
  289. new webpack.EnvironmentPlugin({
  290. // Ensure that process.env.RESET_APP_DATA_TIMER is defined, to avoid an error.
  291. // https://github.com/algolia/algoliasearch-client-javascript/issues/756
  292. RESET_APP_DATA_TIMER: '120000',
  293. // Ensure that process.env.CYPRESS is defined (see utils/worker.js)
  294. CYPRESS: false,
  295. }),
  296. // Prevent moment from loading (very large) locale files that aren't used
  297. new webpack.IgnorePlugin({
  298. resourceRegExp: /^\.\/locale$/,
  299. contextRegExp: /moment$/,
  300. }),
  301. // Set window.$ and window.jQuery
  302. new webpack.ProvidePlugin({
  303. $: 'jquery',
  304. jQuery: 'jquery',
  305. }),
  306. new CopyPlugin({
  307. patterns: [
  308. // Copy the required files for loading MathJax from MathJax NPM package
  309. // https://www.npmjs.com/package/mathjax#user-content-hosting-your-own-copy-of-the-mathjax-components
  310. {
  311. from: 'es5/tex-svg-full.js',
  312. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5`,
  313. toType: 'dir',
  314. context: mathjaxDir,
  315. },
  316. {
  317. from: 'es5/input/tex/extensions/**/*.js',
  318. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  319. toType: 'dir',
  320. context: mathjaxDir,
  321. },
  322. {
  323. from: 'es5/ui/**/*',
  324. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  325. toType: 'dir',
  326. context: mathjaxDir,
  327. },
  328. {
  329. from: 'es5/a11y/**/*',
  330. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  331. toType: 'dir',
  332. context: mathjaxDir,
  333. },
  334. {
  335. from: 'es5/input/mml.js',
  336. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5/input`,
  337. toType: 'dir',
  338. context: mathjaxDir,
  339. },
  340. {
  341. from: 'es5/sre/**/*',
  342. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  343. toType: 'dir',
  344. context: mathjaxDir,
  345. },
  346. {
  347. from: '*',
  348. to: `js/dictionaries/${PackageVersions.version.dictionaries}`,
  349. toType: 'dir',
  350. context: `${dictionariesDir}/dictionaries`,
  351. },
  352. // Copy CMap files (used to provide support for non-Latin characters),
  353. // fonts and images from pdfjs-dist package to build output.
  354. {
  355. from: 'cmaps',
  356. to: 'js/pdfjs-dist/cmaps',
  357. context: pdfjsDir,
  358. },
  359. {
  360. from: 'standard_fonts',
  361. to: 'fonts/pdfjs-dist',
  362. context: pdfjsDir,
  363. },
  364. {
  365. from: 'legacy/web/images',
  366. to: 'images/pdfjs-dist',
  367. context: pdfjsDir,
  368. },
  369. ],
  370. }),
  371. ],
  372. }