webpack.config.ts 20 KB

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