webpack.config.js 13 KB

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