webpack.config.js 13 KB

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