webpack.config.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. const path = require('path')
  2. const glob = 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')
  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. glob
  25. .sync(
  26. path.join(__dirname, 'modules/*/frontend/js/pages/**/*.{js,jsx,ts,tsx}')
  27. )
  28. .forEach(page => {
  29. // in: /workspace/services/web/modules/foo/frontend/js/pages/bar.js
  30. // out: modules/foo/pages/bar
  31. const name = path
  32. .relative(__dirname, page)
  33. .replace(/frontend[/]js[/]/, '')
  34. .replace(/.(js|jsx|ts|tsx)$/, '')
  35. entryPoints[name] = './' + path.relative(__dirname, page)
  36. })
  37. glob
  38. .sync(path.join(__dirname, 'frontend/js/pages/**/*.{js,jsx,ts,tsx}'))
  39. .forEach(page => {
  40. // in: /workspace/services/web/frontend/js/pages/marketing/homepage.ts
  41. // out: pages/marketing/homepage
  42. const name = path
  43. .relative(path.join(__dirname, 'frontend/js/'), page)
  44. .replace(/.(js|jsx|ts|tsx)$/, '')
  45. entryPoints[name] = './' + path.relative(__dirname, page)
  46. })
  47. function getModuleDirectory(moduleName) {
  48. const entrypointPath = require.resolve(moduleName)
  49. const suffix = `node_modules/${moduleName}`
  50. const idx = entrypointPath.indexOf(suffix)
  51. if (idx === -1) {
  52. throw new Error(`could not find Node module: ${moduleName}`)
  53. }
  54. return entrypointPath.slice(0, idx + suffix.length)
  55. }
  56. const mathjaxDir = getModuleDirectory('mathjax')
  57. const pdfjsDir = getModuleDirectory('pdfjs-dist')
  58. const dictionariesDir = getModuleDirectory('@overleaf/dictionaries')
  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. // Output as UMD bundle (allows main JS to import with CJS, AMD or global
  87. // style code bundles
  88. libraryTarget: 'umd',
  89. // Name the exported variable from output bundle
  90. library: ['Frontend', '[name]'],
  91. },
  92. optimization: {
  93. // https://webpack.js.org/plugins/split-chunks-plugin/#splitchunkschunks
  94. splitChunks: {
  95. chunks: 'all', // allow non-async chunks to be analysed for shared modules
  96. },
  97. // https://webpack.js.org/configuration/optimization/#optimizationruntimechunk
  98. runtimeChunk: {
  99. name: 'runtime',
  100. },
  101. },
  102. // Define how file types are handled by webpack
  103. module: {
  104. rules: [
  105. {
  106. test: /\.tsx?$/,
  107. include: path.resolve(
  108. __dirname,
  109. 'modules/writefull/frontend/js/integration'
  110. ),
  111. use: [
  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|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: true,
  142. configFile: path.join(__dirname, './babel.config.json'),
  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. alias: {
  293. // custom prefixes for import paths
  294. '@': path.resolve(__dirname, './frontend/js/'),
  295. '@ol-types': path.resolve(__dirname, './types/'),
  296. '@wf': path.resolve(
  297. __dirname,
  298. './modules/writefull/frontend/js/integration/src/'
  299. ),
  300. },
  301. // symlinks: false, // enable this while using `npm link`
  302. extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'],
  303. fallback: {
  304. events: require.resolve('events'),
  305. // for react-dnd + React 17
  306. 'react/jsx-runtime': 'react/jsx-runtime.js',
  307. 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js',
  308. },
  309. },
  310. experiments: {
  311. asyncWebAssembly: true,
  312. },
  313. plugins: [
  314. new LezerGrammarCompilerPlugin(),
  315. // Generate a manifest.json file which is used by the backend to map the
  316. // base filenames to the generated output filenames
  317. new WebpackAssetsManifest({
  318. entrypoints: true,
  319. publicPath: true,
  320. output: 'manifest.json',
  321. }),
  322. new webpack.EnvironmentPlugin({
  323. // Ensure that process.env.RESET_APP_DATA_TIMER is defined, to avoid an error.
  324. // https://github.com/algolia/algoliasearch-client-javascript/issues/756
  325. RESET_APP_DATA_TIMER: '120000',
  326. // Ensure that process.env.CYPRESS is defined (see utils/worker.js)
  327. CYPRESS: false,
  328. }),
  329. // Prevent moment from loading (very large) locale files that aren't used
  330. new webpack.IgnorePlugin({
  331. resourceRegExp: /^\.\/locale$/,
  332. contextRegExp: /moment$/,
  333. }),
  334. // Set window.$ and window.jQuery
  335. new webpack.ProvidePlugin({
  336. $: 'jquery',
  337. jQuery: 'jquery',
  338. }),
  339. new CopyPlugin({
  340. patterns: [
  341. // Copy the required files for loading MathJax from MathJax NPM package
  342. // https://www.npmjs.com/package/mathjax#user-content-hosting-your-own-copy-of-the-mathjax-components
  343. {
  344. from: 'es5/tex-svg-full.js',
  345. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5`,
  346. toType: 'dir',
  347. context: mathjaxDir,
  348. },
  349. {
  350. from: 'es5/input/tex/extensions/**/*.js',
  351. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  352. toType: 'dir',
  353. context: mathjaxDir,
  354. },
  355. {
  356. from: 'es5/ui/**/*',
  357. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  358. toType: 'dir',
  359. context: mathjaxDir,
  360. },
  361. {
  362. from: 'es5/a11y/**/*',
  363. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  364. toType: 'dir',
  365. context: mathjaxDir,
  366. },
  367. {
  368. from: 'es5/input/mml.js',
  369. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5/input`,
  370. toType: 'dir',
  371. context: mathjaxDir,
  372. },
  373. {
  374. from: 'es5/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 CMap files (used to provide support for non-Latin characters),
  386. // wasm, ICC profiles, fonts and images from pdfjs-dist package to build output.
  387. {
  388. from: 'cmaps',
  389. to: 'js/pdfjs-dist/cmaps',
  390. context: pdfjsDir,
  391. },
  392. {
  393. from: 'iccs',
  394. to: 'js/pdfjs-dist/iccs',
  395. context: pdfjsDir,
  396. },
  397. {
  398. from: 'wasm',
  399. to: 'js/pdfjs-dist/wasm',
  400. context: pdfjsDir,
  401. },
  402. {
  403. from: 'standard_fonts',
  404. to: 'fonts/pdfjs-dist',
  405. context: pdfjsDir,
  406. },
  407. {
  408. from: 'legacy/web/images',
  409. to: 'images/pdfjs-dist',
  410. context: pdfjsDir,
  411. },
  412. ],
  413. }),
  414. ],
  415. }