webpack.config.ts 23 KB

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