webpack.config.ts 21 KB

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