webpack.config.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. const path = require('path')
  2. const { globSync } = 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.js')
  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. 'linkedin-insight': './frontend/js/infrastructure/linkedin-insight.ts',
  23. }
  24. // Add entrypoints for each "page"
  25. globSync(
  26. path.join(__dirname, 'modules/*/frontend/js/pages/**/*.{js,jsx,ts,tsx}')
  27. ).forEach(page => {
  28. // in: /workspace/services/web/modules/foo/frontend/js/pages/bar.js
  29. // out: modules/foo/pages/bar
  30. const name = path
  31. .relative(__dirname, page)
  32. .replace(/frontend[/]js[/]/, '')
  33. .replace(/.(js|jsx|ts|tsx)$/, '')
  34. entryPoints[name] = './' + path.relative(__dirname, page)
  35. })
  36. globSync(
  37. path.join(__dirname, 'frontend/js/pages/**/*.{js,jsx,ts,tsx}')
  38. ).forEach(page => {
  39. // in: /workspace/services/web/frontend/js/pages/marketing/homepage.ts
  40. // out: pages/marketing/homepage
  41. const name = path
  42. .relative(path.join(__dirname, 'frontend/js/'), page)
  43. .replace(/.(js|jsx|ts|tsx)$/, '')
  44. entryPoints[name] = './' + path.relative(__dirname, page)
  45. })
  46. function getModuleDirectory(moduleName) {
  47. try {
  48. return path.dirname(require.resolve(`${moduleName}/package.json`))
  49. } catch (err) {
  50. throw new Error(`could not find Node module: ${moduleName}`, { cause: err })
  51. }
  52. }
  53. const mathjaxDir = getModuleDirectory('mathjax')
  54. const pdfjsDir = getModuleDirectory('pdfjs-dist')
  55. const dictionariesDir = getModuleDirectory('@overleaf/dictionaries')
  56. const pyodideDir = getModuleDirectory('pyodide')
  57. const vendorDir = path.join(__dirname, 'frontend/js/vendor')
  58. const MATHJAX_VERSION = require('mathjax/package.json').version
  59. if (MATHJAX_VERSION !== PackageVersions.version.mathjax) {
  60. throw new Error(
  61. '"mathjax" version de-synced, update services/web/app/src/infrastructure/PackageVersions.js'
  62. )
  63. }
  64. const DICTIONARIES_VERSION =
  65. require('@overleaf/dictionaries/package.json').version
  66. if (DICTIONARIES_VERSION !== PackageVersions.version.dictionaries) {
  67. throw new Error(
  68. '"@overleaf/dictionaries" version de-synced, update services/web/app/src/infrastructure/PackageVersions.js'
  69. )
  70. }
  71. module.exports = {
  72. // Defines the "entry point(s)" for the application - i.e. the file which
  73. // bootstraps the application
  74. entry: entryPoints,
  75. // Define where and how the bundle will be output to disk
  76. // Note: webpack-dev-server does not write the bundle to disk, instead it is
  77. // kept in memory for speed
  78. output: {
  79. path: path.join(__dirname, 'public'),
  80. publicPath: '/',
  81. workerPublicPath: '/',
  82. // By default write into js directory
  83. filename: 'js/[name]-[contenthash].js',
  84. },
  85. optimization: {
  86. // https://webpack.js.org/plugins/split-chunks-plugin/#splitchunkschunks
  87. splitChunks: {
  88. chunks: 'all', // allow non-async chunks to be analysed for shared modules
  89. },
  90. // https://webpack.js.org/configuration/optimization/#optimizationruntimechunk
  91. runtimeChunk: {
  92. name: 'runtime',
  93. },
  94. },
  95. // Define how file types are handled by webpack
  96. module: {
  97. rules: [
  98. {
  99. test: /\.tsx?$/,
  100. include: path.resolve(
  101. __dirname,
  102. 'modules/writefull/frontend/js/integration'
  103. ),
  104. use: [
  105. {
  106. loader: 'babel-loader',
  107. options: {
  108. cacheDirectory: path.join(__dirname, '.cache/babel-loader'),
  109. configFile: path.join(__dirname, './babel.config.cjs'),
  110. },
  111. },
  112. {
  113. loader: 'ts-loader',
  114. options: {
  115. configFile: path.resolve(
  116. __dirname,
  117. 'modules/writefull/frontend/js/integration/tsconfig.json'
  118. ),
  119. transpileOnly: true,
  120. },
  121. },
  122. ],
  123. },
  124. {
  125. // Pass application JS/TS files through babel-loader,
  126. // transpiling to targets defined in browserslist
  127. test: /\.([jt]sx?|[cm]js)$/,
  128. // Only compile application files and specific dependencies
  129. // (other npm and vendored dependencies must be in ES5 already)
  130. exclude: [
  131. /node_modules\/(?!(react-dnd|chart\.js|@uppy|@writefull|pdfjs-dist|react-resizable-panels)\/)/,
  132. vendorDir,
  133. path.resolve(__dirname, 'modules/writefull/frontend/js/integration'),
  134. ],
  135. use: [
  136. {
  137. loader: 'babel-loader',
  138. options: {
  139. // Configure babel-loader to cache compiled output so that
  140. // subsequent compile runs are much faster
  141. cacheDirectory: path.join(__dirname, '.cache/babel-loader'),
  142. configFile: path.join(__dirname, './babel.config.cjs'),
  143. plugins: [
  144. process.env.REACT_REFRESH_ENABLED === 'true' &&
  145. 'react-refresh/babel',
  146. ].filter(Boolean),
  147. },
  148. },
  149. ],
  150. type: 'javascript/auto',
  151. },
  152. {
  153. test: /\.wasm$/,
  154. type: 'asset/resource',
  155. generator: {
  156. filename: 'js/[name]-[contenthash][ext]',
  157. },
  158. },
  159. {
  160. test: /\.txt$/,
  161. type: 'asset/source',
  162. generator: {
  163. filename: 'js/[name]-[contenthash][ext]',
  164. },
  165. },
  166. {
  167. // Pass Sass files through sass-loader/css-loader/mini-css-extract-
  168. // plugin (note: run in reverse order)
  169. test: /\.s[ac]ss$/,
  170. use: [
  171. // Allows the CSS to be extracted to a separate .css file
  172. { loader: MiniCssExtractPlugin.loader },
  173. // Resolves any CSS dependencies (e.g. url())
  174. { loader: 'css-loader' },
  175. // Resolve relative paths sensibly in SASS
  176. { loader: 'resolve-url-loader' },
  177. {
  178. // Runs autoprefixer on CSS via postcss
  179. loader: 'postcss-loader',
  180. options: {
  181. postcssOptions: {
  182. plugins: ['autoprefixer'],
  183. },
  184. },
  185. },
  186. // Compile Sass off the main event loop
  187. {
  188. loader: 'thread-loader',
  189. options: {
  190. // keep workers alive for dev-server, and shut them down when not needed
  191. poolTimeout:
  192. process.env.NODE_ENV === 'development' ? 10 * 60 * 1000 : 500,
  193. // bring up more workers after they timed out
  194. poolRespawn: true,
  195. // limit concurrency (one per entrypoint and let the small includes queue up)
  196. workers: 6,
  197. },
  198. },
  199. // Compiles Sass to CSS
  200. {
  201. loader: 'sass-loader',
  202. options: { sourceMap: true }, // sourceMap: true is required for resolve-url-loader
  203. },
  204. ],
  205. },
  206. {
  207. // Pass CSS files through css-loader & mini-css-extract-plugin (note: run in reverse order)
  208. test: /\.css$/i,
  209. oneOf: [
  210. {
  211. // Import as a string (for Shadow DOM usage): import styles from './file.css?inline'
  212. resourceQuery: /inline/,
  213. use: [
  214. {
  215. loader: 'css-loader',
  216. },
  217. {
  218. loader: 'postcss-loader',
  219. },
  220. ],
  221. },
  222. {
  223. // CSS from writefull module - inject directly into DOM
  224. include: path.resolve(__dirname, 'modules/writefull/'),
  225. use: [
  226. 'style-loader',
  227. {
  228. loader: 'css-loader',
  229. options: {
  230. importLoaders: 1,
  231. },
  232. },
  233. {
  234. loader: 'postcss-loader',
  235. options: {
  236. postcssOptions: {
  237. config: path.resolve(
  238. __dirname,
  239. 'modules/writefull/frontend/js/integration/postcss.config.js'
  240. ),
  241. },
  242. },
  243. },
  244. ],
  245. },
  246. {
  247. // Standard CSS processing (extracted into separate file)
  248. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  249. },
  250. ],
  251. },
  252. {
  253. // Load fonts
  254. test: /\.(woff2?|ttf|otf)$/,
  255. type: 'asset/resource',
  256. generator: {
  257. filename: 'fonts/[name]-[contenthash][ext]',
  258. },
  259. },
  260. {
  261. // Load images and videos (static files)
  262. test: /\.(svg|gif|png|jpg|pdf|mp4)$/,
  263. type: 'asset/resource',
  264. generator: {
  265. filename: 'images/[name]-[contenthash][ext]',
  266. },
  267. },
  268. {
  269. // These options are necessary for handlebars to have access to helper
  270. // methods
  271. test: /\.handlebars$/,
  272. loader: 'handlebars-loader',
  273. options: {
  274. compat: true,
  275. knownHelpersOnly: false,
  276. runtimePath: 'handlebars/runtime',
  277. },
  278. },
  279. {
  280. // Load translations files with custom loader, to extract and apply
  281. // fallbacks
  282. test: /locales\/(\w{2}(-\w{2})?)\.json$/,
  283. use: [
  284. {
  285. loader: path.join(__dirname, 'frontend/translations-loader.js'),
  286. },
  287. ],
  288. },
  289. ],
  290. },
  291. resolve: {
  292. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  293. alias: {
  294. // Ensure all packages use the same jQuery instance (prevents duplicate
  295. // copies from Yarn hoisting breaking jQuery plugins like daterangepicker)
  296. jquery: require.resolve('jquery'),
  297. // Under Yarn PnP, babel-injected core-js polyfill imports cannot be
  298. // resolved from third-party packages (e.g. @uppy, pdfjs-dist) because
  299. // they don't declare core-js as a dependency. Alias to the web
  300. // workspace's copy so all packages can resolve it.
  301. 'core-js': path.dirname(require.resolve('core-js/package.json')),
  302. // writefull's tsconfig uses importHelpers: true, which emits tslib
  303. // imports that must be resolvable from the web workspace.
  304. tslib: path.dirname(require.resolve('tslib/package.json')),
  305. // Under PnP, packages like cypress/react that import react/react-dom
  306. // can't resolve them from their own scope. Alias to web's copies.
  307. react: path.dirname(require.resolve('react/package.json')),
  308. 'react-dom': path.dirname(require.resolve('react-dom/package.json')),
  309. // ai-sdk packages declare zod as a peer dep but PnP can't resolve it
  310. // from their scope in the Docker build.
  311. zod: path.dirname(require.resolve('zod/package.json')),
  312. },
  313. // symlinks: false, // enable this while using `npm link`
  314. extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'],
  315. fallback: {
  316. events: require.resolve('events'),
  317. // for react-dnd + React 17
  318. 'react/jsx-runtime': 'react/jsx-runtime.js',
  319. 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js',
  320. },
  321. },
  322. experiments: {
  323. asyncWebAssembly: true,
  324. },
  325. plugins: [
  326. new LezerGrammarCompilerPlugin(),
  327. // Generate a manifest.json file which is used by the backend to map the
  328. // base filenames to the generated output filenames
  329. new WebpackAssetsManifest({
  330. entrypoints: true,
  331. publicPath: true,
  332. output: 'manifest.json',
  333. }),
  334. new webpack.EnvironmentPlugin({
  335. // Ensure that process.env.RESET_APP_DATA_TIMER is defined, to avoid an error.
  336. // https://github.com/algolia/algoliasearch-client-javascript/issues/756
  337. RESET_APP_DATA_TIMER: '120000',
  338. // Ensure that process.env.CYPRESS is defined (see utils/worker.js)
  339. CYPRESS: false,
  340. }),
  341. // Prevent moment from loading (very large) locale files that aren't used
  342. new webpack.IgnorePlugin({
  343. resourceRegExp: /^\.\/locale$/,
  344. contextRegExp: /moment$/,
  345. }),
  346. // Set window.$ and window.jQuery
  347. new webpack.ProvidePlugin({
  348. $: 'jquery',
  349. jQuery: 'jquery',
  350. }),
  351. new CopyPlugin({
  352. patterns: [
  353. // Copy the required files for loading MathJax from MathJax NPM package
  354. // https://www.npmjs.com/package/mathjax#user-content-hosting-your-own-copy-of-the-mathjax-components
  355. {
  356. from: 'tex-svg.js',
  357. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  358. toType: 'dir',
  359. context: mathjaxDir,
  360. },
  361. {
  362. from: 'input/tex/extensions/**/*.js',
  363. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  364. toType: 'dir',
  365. context: mathjaxDir,
  366. },
  367. {
  368. from: 'ui/**/*',
  369. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  370. toType: 'dir',
  371. context: mathjaxDir,
  372. },
  373. {
  374. from: 'sre/**/*',
  375. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  376. toType: 'dir',
  377. context: mathjaxDir,
  378. },
  379. {
  380. from: '*',
  381. to: `js/dictionaries/${PackageVersions.version.dictionaries}`,
  382. toType: 'dir',
  383. context: `${dictionariesDir}/dictionaries`,
  384. },
  385. // Copy Pyodide runtime assets from the npm package so the loader is
  386. // always available. Python package wheels are fetched separately by
  387. // scripts/fetch-pyodide-packages.mjs into the same directory on disk.
  388. {
  389. from: 'pyodide.mjs',
  390. to: 'js/libs/pyodide',
  391. toType: 'dir',
  392. context: pyodideDir,
  393. },
  394. {
  395. from: 'pyodide.asm.js',
  396. to: 'js/libs/pyodide',
  397. toType: 'dir',
  398. context: pyodideDir,
  399. },
  400. {
  401. from: 'pyodide.asm.wasm',
  402. to: 'js/libs/pyodide',
  403. toType: 'dir',
  404. context: pyodideDir,
  405. },
  406. {
  407. from: 'python_stdlib.zip',
  408. to: 'js/libs/pyodide',
  409. toType: 'dir',
  410. context: pyodideDir,
  411. },
  412. {
  413. from: 'pyodide-lock.json',
  414. to: 'js/libs/pyodide',
  415. toType: 'dir',
  416. context: pyodideDir,
  417. },
  418. // Copy CMap files (used to provide support for non-Latin characters),
  419. // wasm, ICC profiles, fonts and images from pdfjs-dist package to build output.
  420. {
  421. from: 'cmaps',
  422. to: 'js/pdfjs-dist/cmaps',
  423. context: pdfjsDir,
  424. },
  425. {
  426. from: 'iccs',
  427. to: 'js/pdfjs-dist/iccs',
  428. context: pdfjsDir,
  429. },
  430. {
  431. from: 'wasm',
  432. to: 'js/pdfjs-dist/wasm',
  433. context: pdfjsDir,
  434. },
  435. {
  436. from: 'standard_fonts',
  437. to: 'fonts/pdfjs-dist',
  438. context: pdfjsDir,
  439. },
  440. {
  441. from: 'legacy/web/images',
  442. to: 'images/pdfjs-dist',
  443. context: pdfjsDir,
  444. },
  445. ],
  446. }),
  447. ],
  448. }