webpack.config.js 14 KB

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