webpack.config.js 14 KB

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