webpack.config.js 12 KB

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