webpack.config.js 15 KB

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