webpack.config.js 14 KB

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