webpack.config.js 14 KB

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