webpack.config.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /* eslint-env node */
  2. /* eslint import/no-nodejs-modules:0 */
  3. import fs from 'fs';
  4. import path from 'path';
  5. import CompressionPlugin from 'compression-webpack-plugin';
  6. import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
  7. import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
  8. import MiniCssExtractPlugin from 'mini-css-extract-plugin';
  9. import webpack from 'webpack';
  10. import {Configuration as DevServerConfig} from 'webpack-dev-server';
  11. import FixStyleOnlyEntriesPlugin from 'webpack-remove-empty-scripts';
  12. import IntegrationDocsFetchPlugin from './build-utils/integration-docs-fetch-plugin';
  13. import LastBuiltPlugin from './build-utils/last-built-plugin';
  14. import SentryInstrumentation from './build-utils/sentry-instrumentation';
  15. import babelConfig from './babel.config';
  16. /**
  17. * Merges the devServer config into the webpack config
  18. *
  19. * See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43232
  20. */
  21. interface Configuration extends webpack.Configuration {
  22. devServer?: DevServerConfig;
  23. }
  24. const {env} = process;
  25. /**
  26. * Environment configuration
  27. */
  28. const IS_PRODUCTION = env.NODE_ENV === 'production';
  29. const IS_TEST = env.NODE_ENV === 'test' || !!env.TEST_SUITE;
  30. const IS_STORYBOOK = env.STORYBOOK_BUILD === '1';
  31. // This is used to stop rendering dynamic content for tests/snapshots
  32. // We want it in the case where we are running tests and it is in CI,
  33. // this should not happen in local
  34. const IS_CI = !!env.CI;
  35. // We intentionally build in production mode for acceptance tests, so we explicitly use an env var to
  36. // say that the bundle will be used in acceptance tests. This affects webpack plugins and components
  37. // with dynamic data that render differently statically in tests.
  38. //
  39. // Note, cannot assume it is an acceptance test if `IS_CI` is true, as our image builds has the
  40. // `CI` env var set.
  41. const IS_ACCEPTANCE_TEST = !!env.IS_ACCEPTANCE_TEST;
  42. const IS_DEPLOY_PREVIEW = !!env.NOW_GITHUB_DEPLOYMENT;
  43. const IS_UI_DEV_ONLY = !!env.SENTRY_UI_DEV_ONLY;
  44. const DEV_MODE = !(IS_PRODUCTION || IS_CI);
  45. const WEBPACK_MODE: Configuration['mode'] = IS_PRODUCTION ? 'production' : 'development';
  46. /**
  47. * Environment variables that are used by other tooling and should
  48. * not be user configurable.
  49. */
  50. // Ports used by webpack dev server to proxy to backend and webpack
  51. const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
  52. const SENTRY_WEBPACK_PROXY_HOST = env.SENTRY_WEBPACK_PROXY_HOST;
  53. const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
  54. // Used by sentry devserver runner to force using webpack-dev-server
  55. const FORCE_WEBPACK_DEV_SERVER = !!env.FORCE_WEBPACK_DEV_SERVER;
  56. const HAS_WEBPACK_DEV_SERVER_CONFIG =
  57. !!SENTRY_BACKEND_PORT && !!SENTRY_WEBPACK_PROXY_PORT;
  58. /**
  59. * User/tooling configurable environment variables
  60. */
  61. const NO_DEV_SERVER = !!env.NO_DEV_SERVER; // Do not run webpack dev server
  62. const SHOULD_FORK_TS = DEV_MODE && !env.NO_TS_FORK; // Do not run fork-ts plugin (or if not dev env)
  63. const SHOULD_HOT_MODULE_RELOAD = DEV_MODE && !!env.SENTRY_UI_HOT_RELOAD;
  64. // Deploy previews are built using zeit. We can check if we're in zeit's
  65. // build process by checking the existence of the PULL_REQUEST env var.
  66. const DEPLOY_PREVIEW_CONFIG = IS_DEPLOY_PREVIEW && {
  67. branch: env.NOW_GITHUB_COMMIT_REF,
  68. commitSha: env.NOW_GITHUB_COMMIT_SHA,
  69. githubOrg: env.NOW_GITHUB_COMMIT_ORG,
  70. githubRepo: env.NOW_GITHUB_COMMIT_REPO,
  71. };
  72. // When deploy previews are enabled always enable experimental SPA mode --
  73. // deploy previews are served standalone. Otherwise fallback to the environment
  74. // configuration.
  75. const SENTRY_EXPERIMENTAL_SPA =
  76. !DEPLOY_PREVIEW_CONFIG && !IS_UI_DEV_ONLY ? !!env.SENTRY_EXPERIMENTAL_SPA : true;
  77. // We should only read from the SENTRY_SPA_DSN env variable if SENTRY_EXPERIMENTAL_SPA
  78. // is true. This is to make sure we can validate that the experimental SPA mode is
  79. // working properly.
  80. const SENTRY_SPA_DSN = SENTRY_EXPERIMENTAL_SPA ? env.SENTRY_SPA_DSN : undefined;
  81. // this is the path to the django "sentry" app, we output the webpack build here to `dist`
  82. // so that `django collectstatic` and so that we can serve the post-webpack bundles
  83. const sentryDjangoAppPath = path.join(__dirname, 'src/sentry/static/sentry');
  84. const distPath = env.SENTRY_STATIC_DIST_PATH || path.join(sentryDjangoAppPath, 'dist');
  85. const staticPrefix = path.join(__dirname, 'static');
  86. /**
  87. * Locale file extraction build step
  88. */
  89. if (env.SENTRY_EXTRACT_TRANSLATIONS === '1') {
  90. babelConfig.plugins?.push([
  91. 'module:babel-gettext-extractor',
  92. {
  93. fileName: 'build/javascript.po',
  94. baseDirectory: path.join(__dirname, 'src/sentry'),
  95. functionNames: {
  96. gettext: ['msgid'],
  97. ngettext: ['msgid', 'msgid_plural', 'count'],
  98. gettextComponentTemplate: ['msgid'],
  99. t: ['msgid'],
  100. tn: ['msgid', 'msgid_plural', 'count'],
  101. tct: ['msgid'],
  102. },
  103. },
  104. ]);
  105. }
  106. /**
  107. * Locale compilation and optimizations.
  108. *
  109. * Locales are code-split from the app and vendor chunk into separate chunks
  110. * that will be loaded by layout.html depending on the users configured locale.
  111. *
  112. * Code splitting happens using the splitChunks plugin, configured under the
  113. * `optimization` key of the webpack module. We create chunk (cache) groups for
  114. * each of our supported locales and extract the PO files and moment.js locale
  115. * files into each chunk.
  116. *
  117. * A plugin is used to remove the locale chunks from the app entry's chunk
  118. * dependency list, so that our compiled bundle does not expect that *all*
  119. * locale chunks must be loaded
  120. */
  121. const localeCatalogPath = path.join(
  122. __dirname,
  123. 'src',
  124. 'sentry',
  125. 'locale',
  126. 'catalogs.json'
  127. );
  128. type LocaleCatalog = {
  129. supported_locales: string[];
  130. };
  131. const localeCatalog: LocaleCatalog = JSON.parse(
  132. fs.readFileSync(localeCatalogPath, 'utf8')
  133. );
  134. // Translates a locale name to a language code.
  135. //
  136. // * po files are kept in a directory represented by the locale name [0]
  137. // * moment.js locales are stored as language code files
  138. //
  139. // [0] https://docs.djangoproject.com/en/2.1/topics/i18n/#term-locale-name
  140. const localeToLanguage = (locale: string) => locale.toLowerCase().replace('_', '-');
  141. const supportedLocales = localeCatalog.supported_locales;
  142. const supportedLanguages = supportedLocales.map(localeToLanguage);
  143. type CacheGroups = Exclude<
  144. NonNullable<Configuration['optimization']>['splitChunks'],
  145. false | undefined
  146. >['cacheGroups'];
  147. type CacheGroupTest = (
  148. module: webpack.Module,
  149. context: Parameters<webpack.optimize.SplitChunksPlugin['options']['getCacheGroups']>[1]
  150. ) => boolean;
  151. // A mapping of chunk groups used for locale code splitting
  152. const localeChunkGroups: CacheGroups = {};
  153. supportedLocales
  154. // No need to split the english locale out as it will be completely empty and
  155. // is not included in the django layout.html.
  156. .filter(l => l !== 'en')
  157. .forEach(locale => {
  158. const language = localeToLanguage(locale);
  159. const group = `locale/${language}`;
  160. // List of module path tests to group into locale chunks
  161. const localeGroupTests = [
  162. new RegExp(`locale\\/${locale}\\/.*\\.po$`),
  163. new RegExp(`moment\\/locale\\/${language}\\.js$`),
  164. ];
  165. // module test taken from [0] and modified to support testing against
  166. // multiple expressions.
  167. //
  168. // [0] https://github.com/webpack/webpack/blob/7a6a71f1e9349f86833de12a673805621f0fc6f6/lib/optimize/SplitChunksPlugin.js#L309-L320
  169. const groupTest: CacheGroupTest = (module, {chunkGraph}) =>
  170. localeGroupTests.some(pattern =>
  171. pattern.test(module?.nameForCondition?.() ?? '')
  172. ? true
  173. : chunkGraph.getModuleChunks(module).some(c => c.name && pattern.test(c.name))
  174. );
  175. // We are defining a chunk that combines the django language files with
  176. // moment's locales as if you want one, you will want the other.
  177. //
  178. // In the application code you will still need to import via their module
  179. // paths and not the chunk name
  180. localeChunkGroups[group] = {
  181. chunks: 'async',
  182. name: group,
  183. test: groupTest,
  184. enforce: true,
  185. };
  186. });
  187. const babelOptions = {...babelConfig, cacheDirectory: true};
  188. const babelLoaderConfig = {
  189. loader: 'babel-loader',
  190. options: babelOptions,
  191. };
  192. /**
  193. * Main Webpack config for Sentry React SPA.
  194. */
  195. let appConfig: Configuration = {
  196. mode: WEBPACK_MODE,
  197. entry: {
  198. /**
  199. * Main Sentry SPA
  200. *
  201. * The order here matters for `getsentry`
  202. */
  203. app: ['app/utils/statics-setup', 'app'],
  204. /**
  205. * Pipeline View for integrations
  206. */
  207. pipeline: ['app/utils/statics-setup', 'app/views/integrationPipeline'],
  208. /**
  209. * Legacy CSS Webpack appConfig for Django-powered views.
  210. * This generates a single "sentry.css" file that imports ALL component styles
  211. * for use on Django-powered pages.
  212. */
  213. sentry: 'less/sentry.less',
  214. },
  215. context: staticPrefix,
  216. module: {
  217. /**
  218. * XXX: Modifying the order/contents of these rules may break `getsentry`
  219. * Please remember to test it.
  220. */
  221. rules: [
  222. {
  223. test: /\.[tj]sx?$/,
  224. include: [staticPrefix],
  225. exclude: /(vendor|node_modules|dist)/,
  226. use: babelLoaderConfig,
  227. },
  228. {
  229. test: /\.po$/,
  230. use: {
  231. loader: 'po-catalog-loader',
  232. options: {
  233. referenceExtensions: ['.js', '.jsx'],
  234. domain: 'sentry',
  235. },
  236. },
  237. },
  238. {
  239. test: /\.pegjs/,
  240. use: {loader: 'pegjs-loader'},
  241. },
  242. {
  243. test: /\.css/,
  244. use: ['style-loader', 'css-loader'],
  245. },
  246. {
  247. test: /\.less$/,
  248. include: [staticPrefix],
  249. use: [
  250. {
  251. loader: MiniCssExtractPlugin.loader,
  252. options: {
  253. publicPath: 'auto',
  254. },
  255. },
  256. 'css-loader',
  257. 'less-loader',
  258. ],
  259. },
  260. {
  261. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  262. type: 'asset',
  263. },
  264. ],
  265. noParse: [
  266. // don't parse known, pre-built javascript files (improves webpack perf)
  267. /dist\/jquery\.js/,
  268. /jed\/jed\.js/,
  269. /marked\/lib\/marked\.js/,
  270. /terser\/dist\/bundle\.min\.js/,
  271. ],
  272. },
  273. plugins: [
  274. // Do not bundle moment's locale files as we will lazy load them using
  275. // dynamic imports in the application code
  276. new webpack.IgnorePlugin({
  277. contextRegExp: /moment$/,
  278. resourceRegExp: /^\.\/locale$/,
  279. }),
  280. /**
  281. * jQuery must be provided in the global scope specifically and only for
  282. * bootstrap, as it will not import jQuery itself.
  283. *
  284. * We discourage the use of global jQuery through eslint rules
  285. */
  286. new webpack.ProvidePlugin({
  287. jQuery: 'jquery',
  288. process: 'process/browser',
  289. Buffer: ['buffer', 'Buffer'],
  290. }),
  291. /**
  292. * Extract CSS into separate files.
  293. */
  294. new MiniCssExtractPlugin({
  295. // We want the sentry css file to be unversioned for frontend-only deploys
  296. // We will cache using `Cache-Control` headers
  297. filename: 'entrypoints/[name].css',
  298. }),
  299. /**
  300. * Defines environment specific flags.
  301. */
  302. new webpack.DefinePlugin({
  303. 'process.env': {
  304. NODE_ENV: JSON.stringify(env.NODE_ENV),
  305. IS_ACCEPTANCE_TEST: JSON.stringify(IS_ACCEPTANCE_TEST),
  306. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  307. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  308. SPA_DSN: JSON.stringify(SENTRY_SPA_DSN),
  309. },
  310. }),
  311. /**
  312. * This removes empty js files for style only entries (e.g. sentry.less)
  313. */
  314. new FixStyleOnlyEntriesPlugin({verbose: false}),
  315. /**
  316. * Adds build time measurement instrumentation, which will be reported back
  317. * to sentry
  318. */
  319. new SentryInstrumentation(),
  320. ...(SHOULD_FORK_TS
  321. ? [
  322. new ForkTsCheckerWebpackPlugin({
  323. typescript: {
  324. configFile: path.resolve(__dirname, './config/tsconfig.build.json'),
  325. configOverwrite: {
  326. compilerOptions: {incremental: true},
  327. },
  328. },
  329. logger: {devServer: false},
  330. }),
  331. ]
  332. : []),
  333. /**
  334. * Restrict translation files that are pulled in through app/translations.jsx
  335. * and through moment/locale/* to only those which we create bundles for via
  336. * locale/catalogs.json.
  337. *
  338. * Without this, webpack will still output all of the unused locale files despite
  339. * the application never loading any of them.
  340. */
  341. new webpack.ContextReplacementPlugin(
  342. /sentry-locale$/,
  343. path.join(__dirname, 'src', 'sentry', 'locale', path.sep),
  344. true,
  345. new RegExp(`(${supportedLocales.join('|')})/.*\\.po$`)
  346. ),
  347. new webpack.ContextReplacementPlugin(
  348. /moment\/locale/,
  349. new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
  350. ),
  351. ],
  352. resolve: {
  353. alias: {
  354. app: path.join(staticPrefix, 'app'),
  355. 'sentry-images': path.join(staticPrefix, 'images'),
  356. 'sentry-logos': path.join(sentryDjangoAppPath, 'images', 'logos'),
  357. 'sentry-fonts': path.join(staticPrefix, 'fonts'),
  358. // Aliasing this for getsentry's build, otherwise `less/select2` will not be able
  359. // to be resolved
  360. less: path.join(staticPrefix, 'less'),
  361. 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
  362. 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
  363. 'ios-device-list': path.join(
  364. __dirname,
  365. 'node_modules',
  366. 'ios-device-list',
  367. 'dist',
  368. 'ios-device-list.min.js'
  369. ),
  370. },
  371. fallback: {
  372. vm: false,
  373. stream: false,
  374. crypto: require.resolve('crypto-browserify'),
  375. // `yarn why` says this is only needed in dev deps
  376. string_decoder: false,
  377. },
  378. modules: ['node_modules'],
  379. extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
  380. },
  381. output: {
  382. clean: true, // Clean the output directory before emit.
  383. path: distPath,
  384. publicPath: '',
  385. filename: 'entrypoints/[name].js',
  386. chunkFilename: 'chunks/[name].[contenthash].js',
  387. sourceMapFilename: 'sourcemaps/[name].[contenthash].js.map',
  388. assetModuleFilename: 'assets/[name].[contenthash][ext]',
  389. },
  390. optimization: {
  391. chunkIds: 'named',
  392. moduleIds: 'named',
  393. splitChunks: {
  394. // Only affect async chunks, otherwise webpack could potentially split our initial chunks
  395. // Which means the app will not load because we'd need these additional chunks to be loaded in our
  396. // django template.
  397. chunks: 'async',
  398. maxInitialRequests: 10, // (default: 30)
  399. maxAsyncRequests: 10, // (default: 30)
  400. cacheGroups: {
  401. ...localeChunkGroups,
  402. },
  403. },
  404. // This only runs in production mode
  405. // Grabbed this example from https://github.com/webpack-contrib/css-minimizer-webpack-plugin
  406. minimizer: ['...', new CssMinimizerPlugin()],
  407. },
  408. devtool: IS_PRODUCTION ? 'source-map' : 'eval-cheap-module-source-map',
  409. };
  410. if (IS_TEST || IS_ACCEPTANCE_TEST || IS_STORYBOOK) {
  411. appConfig.resolve!.alias!['integration-docs-platforms'] = path.join(
  412. __dirname,
  413. 'tests/fixtures/integration-docs/_platforms.json'
  414. );
  415. } else {
  416. const plugin = new IntegrationDocsFetchPlugin({basePath: __dirname});
  417. appConfig.plugins?.push(plugin);
  418. appConfig.resolve!.alias!['integration-docs-platforms'] = plugin.modulePath;
  419. }
  420. if (IS_ACCEPTANCE_TEST) {
  421. appConfig.plugins?.push(new LastBuiltPlugin({basePath: __dirname}));
  422. }
  423. // Dev only! Hot module reloading
  424. if (
  425. FORCE_WEBPACK_DEV_SERVER ||
  426. (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
  427. IS_UI_DEV_ONLY
  428. ) {
  429. if (SHOULD_HOT_MODULE_RELOAD) {
  430. // Hot reload react components on save
  431. // We include the library here as to not break docker/google cloud builds
  432. // since we do not install devDeps there.
  433. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  434. appConfig.plugins?.push(new ReactRefreshWebpackPlugin());
  435. }
  436. appConfig.devServer = {
  437. headers: {
  438. 'Access-Control-Allow-Origin': '*',
  439. 'Access-Control-Allow-Credentials': 'true',
  440. },
  441. // Required for getsentry
  442. disableHostCheck: true,
  443. contentBase: './src/sentry/static/sentry',
  444. host: SENTRY_WEBPACK_PROXY_HOST,
  445. hot: true,
  446. // If below is false, will reload on errors
  447. hotOnly: true,
  448. port: Number(SENTRY_WEBPACK_PROXY_PORT),
  449. stats: 'errors-only',
  450. overlay: false,
  451. watchOptions: {
  452. ignored: ['node_modules'],
  453. },
  454. };
  455. if (!IS_UI_DEV_ONLY) {
  456. // This proxies to local backend server
  457. const backendAddress = `http://localhost:${SENTRY_BACKEND_PORT}/`;
  458. const relayAddress = 'http://127.0.0.1:7899';
  459. appConfig.devServer = {
  460. ...appConfig.devServer,
  461. publicPath: '/_static/dist/sentry',
  462. // syntax for matching is using https://www.npmjs.com/package/micromatch
  463. proxy: {
  464. '/api/store/**': relayAddress,
  465. '/api/{1..9}*({0..9})/**': relayAddress,
  466. '/api/0/relays/outcomes/': relayAddress,
  467. '!/_static/dist/sentry/**': backendAddress,
  468. },
  469. };
  470. }
  471. }
  472. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  473. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  474. // backend (in this case, sentry.io), otherwise ALL requests are rewritten
  475. // to a development index.html -- thus, completely separating the frontend
  476. // from serving any pages through the backend.
  477. //
  478. // THIS IS EXPERIMENTAL and has limitations (e.g. you can't use SSO)
  479. //
  480. // Various sentry pages still rely on django to serve html views.
  481. if (IS_UI_DEV_ONLY) {
  482. // Try and load certificates from mkcert if available. Use $ yarn mkcert-localhost
  483. const certPath = path.join(__dirname, 'config');
  484. const https = !fs.existsSync(path.join(certPath, 'localhost.pem'))
  485. ? true
  486. : {
  487. key: fs.readFileSync(path.join(certPath, 'localhost-key.pem')),
  488. cert: fs.readFileSync(path.join(certPath, 'localhost.pem')),
  489. };
  490. appConfig.devServer = {
  491. ...appConfig.devServer,
  492. compress: true,
  493. https,
  494. publicPath: '/_assets/',
  495. proxy: [
  496. {
  497. context: ['/api/', '/avatar/', '/organization-avatar/'],
  498. target: 'https://sentry.io',
  499. secure: false,
  500. changeOrigin: true,
  501. headers: {
  502. Referer: 'https://sentry.io/',
  503. },
  504. },
  505. ],
  506. historyApiFallback: {
  507. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  508. },
  509. };
  510. }
  511. if (IS_UI_DEV_ONLY || IS_DEPLOY_PREVIEW) {
  512. appConfig.output!.publicPath = '/_assets/';
  513. /**
  514. * Generate a index.html file used for running the app in pure client mode.
  515. * This is currently used for PR deploy previews, where only the frontend
  516. * is deployed.
  517. */
  518. const HtmlWebpackPlugin = require('html-webpack-plugin');
  519. appConfig.plugins?.push(
  520. new HtmlWebpackPlugin({
  521. // Local dev vs vercel slightly differs...
  522. ...(IS_UI_DEV_ONLY
  523. ? {devServer: `https://localhost:${SENTRY_WEBPACK_PROXY_PORT}`}
  524. : {}),
  525. favicon: path.resolve(sentryDjangoAppPath, 'images', 'favicon_dev.png'),
  526. template: path.resolve(staticPrefix, 'index.ejs'),
  527. mobile: true,
  528. excludeChunks: ['pipeline'],
  529. title: 'Sentry',
  530. })
  531. );
  532. }
  533. const minificationPlugins = [
  534. // This compression-webpack-plugin generates pre-compressed files
  535. // ending in .gz, to be picked up and served by our internal static media
  536. // server as well as nginx when paired with the gzip_static module.
  537. //
  538. // TODO(ts): The current @types/compression-webpack-plugin is still targeting
  539. // webpack@4, for now we just as any it.
  540. new CompressionPlugin({
  541. algorithm: 'gzip',
  542. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  543. }) as any,
  544. // NOTE: In production mode webpack will automatically minify javascript
  545. // using the TerserWebpackPlugin.
  546. ];
  547. if (IS_PRODUCTION) {
  548. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  549. minificationPlugins.forEach(plugin => appConfig.plugins?.push(plugin));
  550. }
  551. // Cache webpack builds
  552. if (env.WEBPACK_CACHE_PATH) {
  553. appConfig.cache = {
  554. type: 'filesystem',
  555. cacheLocation: path.resolve(__dirname, env.WEBPACK_CACHE_PATH),
  556. buildDependencies: {
  557. // This makes all dependencies of this file - build dependencies
  558. config: [__filename],
  559. // By default webpack and loaders are build dependencies
  560. },
  561. };
  562. }
  563. if (env.MEASURE) {
  564. const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
  565. const smp = new SpeedMeasurePlugin();
  566. appConfig = smp.wrap(appConfig);
  567. }
  568. export default appConfig;