webpack.config.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. // Standard CSS processing (extracted into separate file)
  224. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  225. },
  226. ],
  227. },
  228. {
  229. // Load fonts
  230. test: /\.(woff2?|ttf|otf)$/,
  231. type: 'asset/resource',
  232. generator: {
  233. filename: 'fonts/[name]-[contenthash][ext]',
  234. },
  235. },
  236. {
  237. // Load images and videos (static files)
  238. test: /\.(svg|gif|png|jpg|pdf|mp4)$/,
  239. type: 'asset/resource',
  240. generator: {
  241. filename: 'images/[name]-[contenthash][ext]',
  242. },
  243. },
  244. {
  245. // These options are necessary for handlebars to have access to helper
  246. // methods
  247. test: /\.handlebars$/,
  248. loader: 'handlebars-loader',
  249. options: {
  250. compat: true,
  251. knownHelpersOnly: false,
  252. runtimePath: 'handlebars/runtime',
  253. },
  254. },
  255. {
  256. // Load translations files with custom loader, to extract and apply
  257. // fallbacks
  258. test: /locales\/(\w{2}(-\w{2})?)\.json$/,
  259. use: [
  260. {
  261. loader: path.join(__dirname, 'frontend/translations-loader.js'),
  262. },
  263. ],
  264. },
  265. ],
  266. },
  267. resolve: {
  268. alias: {
  269. // custom prefixes for import paths
  270. '@': path.resolve(__dirname, './frontend/js/'),
  271. '@ol-types': path.resolve(__dirname, './types/'),
  272. '@wf': path.resolve(
  273. __dirname,
  274. './modules/writefull/frontend/js/integration/src/'
  275. ),
  276. },
  277. // symlinks: false, // enable this while using `npm link`
  278. extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'],
  279. fallback: {
  280. events: require.resolve('events'),
  281. // for react-dnd + React 17
  282. 'react/jsx-runtime': 'react/jsx-runtime.js',
  283. 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js',
  284. },
  285. },
  286. experiments: {
  287. asyncWebAssembly: true,
  288. },
  289. plugins: [
  290. new LezerGrammarCompilerPlugin(),
  291. // Generate a manifest.json file which is used by the backend to map the
  292. // base filenames to the generated output filenames
  293. new WebpackAssetsManifest({
  294. entrypoints: true,
  295. publicPath: true,
  296. output: 'manifest.json',
  297. }),
  298. new webpack.EnvironmentPlugin({
  299. // Ensure that process.env.RESET_APP_DATA_TIMER is defined, to avoid an error.
  300. // https://github.com/algolia/algoliasearch-client-javascript/issues/756
  301. RESET_APP_DATA_TIMER: '120000',
  302. // Ensure that process.env.CYPRESS is defined (see utils/worker.js)
  303. CYPRESS: false,
  304. }),
  305. // Prevent moment from loading (very large) locale files that aren't used
  306. new webpack.IgnorePlugin({
  307. resourceRegExp: /^\.\/locale$/,
  308. contextRegExp: /moment$/,
  309. }),
  310. // Set window.$ and window.jQuery
  311. new webpack.ProvidePlugin({
  312. $: 'jquery',
  313. jQuery: 'jquery',
  314. }),
  315. new CopyPlugin({
  316. patterns: [
  317. // Copy the required files for loading MathJax from MathJax NPM package
  318. // https://www.npmjs.com/package/mathjax#user-content-hosting-your-own-copy-of-the-mathjax-components
  319. {
  320. from: 'es5/tex-svg-full.js',
  321. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5`,
  322. toType: 'dir',
  323. context: mathjaxDir,
  324. },
  325. {
  326. from: 'es5/input/tex/extensions/**/*.js',
  327. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  328. toType: 'dir',
  329. context: mathjaxDir,
  330. },
  331. {
  332. from: 'es5/ui/**/*',
  333. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  334. toType: 'dir',
  335. context: mathjaxDir,
  336. },
  337. {
  338. from: 'es5/a11y/**/*',
  339. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  340. toType: 'dir',
  341. context: mathjaxDir,
  342. },
  343. {
  344. from: 'es5/input/mml.js',
  345. to: `js/libs/mathjax-${PackageVersions.version.mathjax}/es5/input`,
  346. toType: 'dir',
  347. context: mathjaxDir,
  348. },
  349. {
  350. from: 'es5/sre/**/*',
  351. to: `js/libs/mathjax-${PackageVersions.version.mathjax}`,
  352. toType: 'dir',
  353. context: mathjaxDir,
  354. },
  355. {
  356. from: '*',
  357. to: `js/dictionaries/${PackageVersions.version.dictionaries}`,
  358. toType: 'dir',
  359. context: `${dictionariesDir}/dictionaries`,
  360. },
  361. // Copy CMap files (used to provide support for non-Latin characters),
  362. // wasm, ICC profiles, fonts and images from pdfjs-dist package to build output.
  363. {
  364. from: 'cmaps',
  365. to: 'js/pdfjs-dist/cmaps',
  366. context: pdfjsDir,
  367. },
  368. {
  369. from: 'iccs',
  370. to: 'js/pdfjs-dist/iccs',
  371. context: pdfjsDir,
  372. },
  373. {
  374. from: 'wasm',
  375. to: 'js/pdfjs-dist/wasm',
  376. context: pdfjsDir,
  377. },
  378. {
  379. from: 'standard_fonts',
  380. to: 'fonts/pdfjs-dist',
  381. context: pdfjsDir,
  382. },
  383. {
  384. from: 'legacy/web/images',
  385. to: 'images/pdfjs-dist',
  386. context: pdfjsDir,
  387. },
  388. ],
  389. }),
  390. ],
  391. }