webpack.config.js 13 KB

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