webpack.config.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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. const {StatsWriterPlugin} = require('webpack-stats-plugin');
  14. import IntegrationDocsFetchPlugin from './build-utils/integration-docs-fetch-plugin';
  15. import LastBuiltPlugin from './build-utils/last-built-plugin';
  16. import SentryInstrumentation from './build-utils/sentry-instrumentation';
  17. import {extractIOSDeviceNames} from './scripts/extract-ios-device-names';
  18. import babelConfig from './babel.config';
  19. // Runs as part of prebuild step to generate a list of identifier -> name mappings for iOS
  20. (async () => {
  21. await extractIOSDeviceNames();
  22. })();
  23. /**
  24. * Merges the devServer config into the webpack config
  25. *
  26. * See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43232
  27. */
  28. interface Configuration extends webpack.Configuration {
  29. devServer?: DevServerConfig;
  30. }
  31. const {env} = process;
  32. // Environment configuration
  33. env.NODE_ENV = env.NODE_ENV ?? 'development';
  34. const IS_PRODUCTION = env.NODE_ENV === 'production';
  35. const IS_TEST = env.NODE_ENV === 'test' || !!env.TEST_SUITE;
  36. // This is used to stop rendering dynamic content for tests/snapshots
  37. // We want it in the case where we are running tests and it is in CI,
  38. // this should not happen in local
  39. const IS_CI = !!env.CI;
  40. // We intentionally build in production mode for acceptance tests, so we explicitly use an env var to
  41. // say that the bundle will be used in acceptance tests. This affects webpack plugins and components
  42. // with dynamic data that render differently statically in tests.
  43. //
  44. // Note, cannot assume it is an acceptance test if `IS_CI` is true, as our image builds has the
  45. // `CI` env var set.
  46. const IS_ACCEPTANCE_TEST = !!env.IS_ACCEPTANCE_TEST;
  47. const IS_DEPLOY_PREVIEW = !!env.NOW_GITHUB_DEPLOYMENT;
  48. const IS_UI_DEV_ONLY = !!env.SENTRY_UI_DEV_ONLY;
  49. const DEV_MODE = !(IS_PRODUCTION || IS_CI);
  50. const WEBPACK_MODE: Configuration['mode'] = IS_PRODUCTION ? 'production' : 'development';
  51. const CONTROL_SILO_PORT = env.SENTRY_CONTROL_SILO_PORT;
  52. // Environment variables that are used by other tooling and should
  53. // not be user configurable.
  54. //
  55. // Ports used by webpack dev server to proxy to backend and webpack
  56. const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
  57. const SENTRY_WEBPACK_PROXY_HOST = env.SENTRY_WEBPACK_PROXY_HOST;
  58. const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
  59. const SENTRY_RELEASE_VERSION = env.SENTRY_RELEASE_VERSION;
  60. // Used by sentry devserver runner to force using webpack-dev-server
  61. const FORCE_WEBPACK_DEV_SERVER = !!env.FORCE_WEBPACK_DEV_SERVER;
  62. const HAS_WEBPACK_DEV_SERVER_CONFIG =
  63. !!SENTRY_BACKEND_PORT && !!SENTRY_WEBPACK_PROXY_PORT;
  64. // User/tooling configurable environment variables
  65. const NO_DEV_SERVER = !!env.NO_DEV_SERVER; // Do not run webpack dev server
  66. const SHOULD_FORK_TS = DEV_MODE && !env.NO_TS_FORK; // Do not run fork-ts plugin (or if not dev env)
  67. const SHOULD_HOT_MODULE_RELOAD = DEV_MODE && !!env.SENTRY_UI_HOT_RELOAD;
  68. const SHOULD_LAZY_LOAD = DEV_MODE && !!env.SENTRY_UI_LAZY_LOAD;
  69. // Deploy previews are built using vercel. We can check if we're in vercel's
  70. // build process by checking the existence of the PULL_REQUEST env var.
  71. const DEPLOY_PREVIEW_CONFIG = IS_DEPLOY_PREVIEW && {
  72. branch: env.NOW_GITHUB_COMMIT_REF,
  73. commitSha: env.NOW_GITHUB_COMMIT_SHA,
  74. githubOrg: env.NOW_GITHUB_COMMIT_ORG,
  75. githubRepo: env.NOW_GITHUB_COMMIT_REPO,
  76. };
  77. // When deploy previews are enabled always enable experimental SPA mode --
  78. // deploy previews are served standalone. Otherwise fallback to the environment
  79. // configuration.
  80. const SENTRY_EXPERIMENTAL_SPA =
  81. !DEPLOY_PREVIEW_CONFIG && !IS_UI_DEV_ONLY ? !!env.SENTRY_EXPERIMENTAL_SPA : true;
  82. // We should only read from the SENTRY_SPA_DSN env variable if SENTRY_EXPERIMENTAL_SPA
  83. // is true. This is to make sure we can validate that the experimental SPA mode is
  84. // working properly.
  85. const SENTRY_SPA_DSN = SENTRY_EXPERIMENTAL_SPA ? env.SENTRY_SPA_DSN : undefined;
  86. // this is the path to the django "sentry" app, we output the webpack build here to `dist`
  87. // so that `django collectstatic` and so that we can serve the post-webpack bundles
  88. const sentryDjangoAppPath = path.join(__dirname, 'src/sentry/static/sentry');
  89. const distPath = env.SENTRY_STATIC_DIST_PATH || path.join(sentryDjangoAppPath, 'dist');
  90. const staticPrefix = path.join(__dirname, 'static');
  91. // Locale file extraction build step
  92. if (env.SENTRY_EXTRACT_TRANSLATIONS === '1') {
  93. babelConfig.plugins?.push([
  94. 'module:babel-gettext-extractor',
  95. {
  96. fileName: 'build/javascript.po',
  97. baseDirectory: path.join(__dirname),
  98. functionNames: {
  99. gettext: ['msgid'],
  100. ngettext: ['msgid', 'msgid_plural', 'count'],
  101. gettextComponentTemplate: ['msgid'],
  102. t: ['msgid'],
  103. tn: ['msgid', 'msgid_plural', 'count'],
  104. tct: ['msgid'],
  105. },
  106. },
  107. ]);
  108. }
  109. // Locale compilation and optimizations.
  110. //
  111. // Locales are code-split from the app and vendor chunk into separate chunks
  112. // that will be loaded by layout.html depending on the users configured locale.
  113. //
  114. // Code splitting happens using the splitChunks plugin, configured under the
  115. // `optimization` key of the webpack module. We create chunk (cache) groups for
  116. // each of our supported locales and extract the PO files and moment.js locale
  117. // files into each chunk.
  118. //
  119. // A plugin is used to remove the locale chunks from the app entry's chunk
  120. // dependency list, so that our compiled bundle does not expect that *all*
  121. // locale chunks must be loaded
  122. const localeCatalogPath = path.join(
  123. __dirname,
  124. 'src',
  125. 'sentry',
  126. 'locale',
  127. 'catalogs.json'
  128. );
  129. type LocaleCatalog = {
  130. supported_locales: string[];
  131. };
  132. const localeCatalog: LocaleCatalog = JSON.parse(
  133. fs.readFileSync(localeCatalogPath, 'utf8')
  134. );
  135. // Translates a locale name to a language code.
  136. //
  137. // * po files are kept in a directory represented by the locale name [0]
  138. // * moment.js locales are stored as language code files
  139. //
  140. // [0] https://docs.djangoproject.com/en/2.1/topics/i18n/#term-locale-name
  141. const localeToLanguage = (locale: string) => locale.toLowerCase().replace('_', '-');
  142. const supportedLocales = localeCatalog.supported_locales;
  143. const supportedLanguages = supportedLocales.map(localeToLanguage);
  144. type CacheGroups = Exclude<
  145. NonNullable<Configuration['optimization']>['splitChunks'],
  146. false | undefined
  147. >['cacheGroups'];
  148. type CacheGroupTest = (
  149. module: webpack.Module,
  150. context: Parameters<webpack.optimize.SplitChunksPlugin['options']['getCacheGroups']>[1]
  151. ) => boolean;
  152. // A mapping of chunk groups used for locale code splitting
  153. const localeChunkGroups: CacheGroups = {};
  154. supportedLocales
  155. // No need to split the english locale out as it will be completely empty and
  156. // is not included in the django layout.html.
  157. .filter(l => l !== 'en')
  158. .forEach(locale => {
  159. const language = localeToLanguage(locale);
  160. const group = `locale/${language}`;
  161. // List of module path tests to group into locale chunks
  162. const localeGroupTests = [
  163. new RegExp(`locale\\/${locale}\\/.*\\.po$`),
  164. new RegExp(`moment\\/locale\\/${language}\\.js$`),
  165. ];
  166. // module test taken from [0] and modified to support testing against
  167. // multiple expressions.
  168. //
  169. // [0] https://github.com/webpack/webpack/blob/7a6a71f1e9349f86833de12a673805621f0fc6f6/lib/optimize/SplitChunksPlugin.js#L309-L320
  170. const groupTest: CacheGroupTest = (module, {chunkGraph}) =>
  171. localeGroupTests.some(pattern =>
  172. pattern.test(module?.nameForCondition?.() ?? '')
  173. ? true
  174. : chunkGraph.getModuleChunks(module).some(c => c.name && pattern.test(c.name))
  175. );
  176. // We are defining a chunk that combines the django language files with
  177. // moment's locales as if you want one, you will want the other.
  178. //
  179. // In the application code you will still need to import via their module
  180. // paths and not the chunk name
  181. localeChunkGroups[group] = {
  182. chunks: 'async',
  183. name: group,
  184. test: groupTest,
  185. enforce: true,
  186. };
  187. });
  188. const babelOptions = {...babelConfig, cacheDirectory: true};
  189. const babelLoaderConfig = {
  190. loader: 'babel-loader',
  191. options: babelOptions,
  192. };
  193. /**
  194. * Main Webpack config for Sentry React SPA.
  195. */
  196. const appConfig: Configuration = {
  197. mode: WEBPACK_MODE,
  198. entry: {
  199. /**
  200. * Main Sentry SPA
  201. *
  202. * The order here matters for `getsentry`
  203. */
  204. app: ['sentry/utils/statics-setup', 'sentry'],
  205. /**
  206. * Pipeline View for integrations
  207. */
  208. pipeline: ['sentry/utils/statics-setup', 'sentry/views/integrationPipeline'],
  209. /**
  210. * Legacy CSS Webpack appConfig for Django-powered views.
  211. * This generates a single "sentry.css" file that imports ALL component styles
  212. * for use on Django-powered pages.
  213. */
  214. sentry: 'less/sentry.less',
  215. },
  216. context: staticPrefix,
  217. module: {
  218. /**
  219. * XXX: Modifying the order/contents of these rules may break `getsentry`
  220. * Please remember to test it.
  221. */
  222. rules: [
  223. {
  224. test: /\.[tj]sx?$/,
  225. include: [staticPrefix],
  226. exclude: /(vendor|node_modules|dist)/,
  227. use: babelLoaderConfig,
  228. },
  229. {
  230. test: /\.po$/,
  231. use: {
  232. loader: 'po-catalog-loader',
  233. options: {
  234. referenceExtensions: ['.js', '.jsx', '.tsx'],
  235. domain: 'sentry',
  236. },
  237. },
  238. },
  239. {
  240. test: /\.pegjs/,
  241. use: {loader: 'pegjs-loader'},
  242. },
  243. {
  244. test: /\.css/,
  245. use: [
  246. 'style-loader',
  247. {
  248. loader: 'css-loader',
  249. options: {
  250. importLoaders: 1,
  251. modules: true,
  252. },
  253. },
  254. ],
  255. },
  256. {
  257. test: /\.less$/,
  258. include: [staticPrefix],
  259. use: [
  260. {
  261. loader: MiniCssExtractPlugin.loader,
  262. options: {
  263. publicPath: 'auto',
  264. },
  265. },
  266. 'css-loader',
  267. 'less-loader',
  268. ],
  269. },
  270. {
  271. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  272. type: 'asset',
  273. },
  274. ],
  275. noParse: [
  276. // don't parse known, pre-built javascript files (improves webpack perf)
  277. /jed\/jed\.js/,
  278. /marked\/lib\/marked\.js/,
  279. /terser\/dist\/bundle\.min\.js/,
  280. ],
  281. },
  282. plugins: [
  283. /**
  284. * Adds build time measurement instrumentation, which will be reported back
  285. * to sentry
  286. */
  287. new SentryInstrumentation(),
  288. // Do not bundle moment's locale files as we will lazy load them using
  289. // dynamic imports in the application code
  290. new webpack.IgnorePlugin({
  291. contextRegExp: /moment$/,
  292. resourceRegExp: /^\.\/locale$/,
  293. }),
  294. /**
  295. * TODO(epurkhiser): Figure out if we still need these
  296. */
  297. new webpack.ProvidePlugin({
  298. process: 'process/browser',
  299. Buffer: ['buffer', 'Buffer'],
  300. }),
  301. /**
  302. * Extract CSS into separate files.
  303. */
  304. new MiniCssExtractPlugin({
  305. // We want the sentry css file to be unversioned for frontend-only deploys
  306. // We will cache using `Cache-Control` headers
  307. filename: 'entrypoints/[name].css',
  308. }),
  309. /**
  310. * Defines environment specific flags.
  311. */
  312. new webpack.DefinePlugin({
  313. 'process.env': {
  314. NODE_ENV: JSON.stringify(env.NODE_ENV),
  315. IS_ACCEPTANCE_TEST: JSON.stringify(IS_ACCEPTANCE_TEST),
  316. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  317. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  318. SPA_DSN: JSON.stringify(SENTRY_SPA_DSN),
  319. SENTRY_RELEASE_VERSION: JSON.stringify(SENTRY_RELEASE_VERSION),
  320. },
  321. }),
  322. /**
  323. * This removes empty js files for style only entries (e.g. sentry.less)
  324. */
  325. new FixStyleOnlyEntriesPlugin({verbose: false}),
  326. ...(SHOULD_FORK_TS
  327. ? [
  328. new ForkTsCheckerWebpackPlugin({
  329. typescript: {
  330. configFile: path.resolve(__dirname, './config/tsconfig.build.json'),
  331. configOverwrite: {
  332. compilerOptions: {incremental: true},
  333. },
  334. },
  335. devServer: false,
  336. // memorylimit is configured in package.json
  337. }),
  338. ]
  339. : []),
  340. /**
  341. * Restrict translation files that are pulled in through app/translations.jsx
  342. * and through moment/locale/* to only those which we create bundles for via
  343. * locale/catalogs.json.
  344. *
  345. * Without this, webpack will still output all of the unused locale files despite
  346. * the application never loading any of them.
  347. */
  348. new webpack.ContextReplacementPlugin(
  349. /sentry-locale$/,
  350. path.join(__dirname, 'src', 'sentry', 'locale', path.sep),
  351. true,
  352. new RegExp(`(${supportedLocales.join('|')})/.*\\.po$`)
  353. ),
  354. new webpack.ContextReplacementPlugin(
  355. /moment\/locale/,
  356. new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
  357. ),
  358. /**
  359. * Copies file logo-sentry.svg to the dist/entrypoints directory so that it can be accessed by
  360. * the backend
  361. */
  362. new CopyPlugin({
  363. patterns: [
  364. {
  365. from: path.join(staticPrefix, 'images/logo-sentry.svg'),
  366. to: 'entrypoints/logo-sentry.svg',
  367. toType: 'file',
  368. },
  369. // Add robots.txt when deploying in preview mode so public previews do
  370. // not get indexed by bots.
  371. ...(IS_DEPLOY_PREVIEW
  372. ? [
  373. {
  374. from: path.join(staticPrefix, 'robots-dev.txt'),
  375. to: 'robots.txt',
  376. toType: 'file' as const,
  377. },
  378. ]
  379. : []),
  380. ],
  381. }),
  382. // Generates stats to src/sentry/static/sentry/dist/stats.json
  383. new StatsWriterPlugin({
  384. stats: {
  385. hash: true,
  386. assets: true,
  387. chunks: true,
  388. modules: true,
  389. env: true,
  390. entrypoints: true,
  391. chunkModules: true,
  392. },
  393. transform(data: webpack.StatsCompilation) {
  394. data.namedChunkGroups;
  395. const finalData: Record<string, any> = {
  396. version: data.version,
  397. hash: data.hash,
  398. entrypoints: data.entrypoints,
  399. env: data.env,
  400. assetsByChunkName: data.assetsByChunkName,
  401. };
  402. // Based on https://github.com/relative-ci/bundle-stats/tree/master/packages/plugin-webpack-filter
  403. // # The MIT License
  404. // Copyright 2019 Viorel Cojocaru, contributors
  405. //
  406. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software
  407. // and associated documentation files (the 'Software'), to deal in the Software without restriction, including
  408. // without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  409. // of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
  410. // conditions:
  411. //
  412. // The above copyright notice and this permission notice shall be included in all copies or substantial
  413. // portions of the Software.
  414. //
  415. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  416. // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  417. // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  418. // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  419. // DEALINGS IN THE SOFTWARE.
  420. // {
  421. // "chunkNames": [], // The chunks this asset contains
  422. // "chunks": [10, 6], // The chunk IDs this asset contains
  423. // "comparedForEmit": false, // Indicates whether or not the asset was compared with the same file on the output file system
  424. // "emitted": true, // Indicates whether or not the asset made it to the `output` directory
  425. // "name": "10.web.js", // The `output` filename
  426. // "size": 1058, // The size of the file in bytes
  427. // "info": {
  428. // "immutable": true, // A flag telling whether the asset can be long term cached (contains a hash)
  429. // "size": 1058, // The size in bytes, only becomes available after asset has been emitted
  430. // "development": true, // A flag telling whether the asset is only used for development and doesn't count towards user-facing assets
  431. // "hotModuleReplacement": true, // A flag telling whether the asset ships data for updating an existing application (HMR)
  432. // "sourceFilename": "originalfile.js", // sourceFilename when asset was created from a source file (potentially transformed)
  433. // "javascriptModule": true // true, when asset is javascript and an ESM
  434. // }
  435. // }
  436. if (data.assets) {
  437. finalData.assets = data.assets.reduce((acc, asset) => {
  438. if (asset.name && !/.map$/.test(asset.name)) {
  439. acc.push({
  440. name: asset.name,
  441. size: asset.size,
  442. info: asset.info,
  443. ...(asset.chunks && {chunks: asset.chunks}),
  444. });
  445. }
  446. return acc;
  447. }, [] as Array<Pick<webpack.StatsAsset, 'name' | 'size' | 'info' | 'chunks'>>);
  448. }
  449. // {
  450. // "entry": true, // Indicates whether or not the chunk contains the webpack runtime
  451. // "files": [
  452. // // An array of filename strings that contain this chunk
  453. // ],
  454. // "filteredModules": 0, // See the description in the [top-level structure](#structure) above
  455. // "id": 0, // The ID of this chunk
  456. // "initial": true, // Indicates whether this chunk is loaded on initial page load or [on demand](/guides/lazy-loading)
  457. // "modules": [
  458. // // A list of [module objects](#module-objects)
  459. // "web.js?h=11593e3b3ac85436984a"
  460. // ],
  461. // "names": [
  462. // // An list of chunk names contained within this chunk
  463. // ],
  464. // "origins": [
  465. // {
  466. // "loc": "", // Lines of code that generated this chunk
  467. // "module": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module
  468. // "moduleId": 0, // The ID of the module
  469. // "moduleIdentifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module
  470. // "moduleName": "./lib/index.web.js", // Relative path to the module
  471. // "name": "main", // The name of the chunk
  472. // "reasons": [
  473. // // A list of the same `reasons` found in [module objects](#module-objects)
  474. // ]
  475. // }
  476. // ],
  477. // "parents": [], // Parent chunk IDs
  478. // "rendered": true, // Indicates whether or not the chunk went through Code Generation
  479. // "size": 188057 // Chunk size in bytes
  480. // }
  481. if (data.chunks) {
  482. finalData.chunks = data.chunks.reduce((acc, chunk) => {
  483. if (!chunk.id) {
  484. return acc;
  485. }
  486. acc.push({
  487. entry: chunk.entry,
  488. id: chunk.id,
  489. size: chunk.size,
  490. initial: chunk.initial,
  491. files: chunk.files,
  492. names: chunk.names,
  493. ...(chunk.modules && {
  494. modules: chunk.modules.map(m => ({
  495. name: m.name,
  496. size: m.size,
  497. id: m.id,
  498. identifier: m.identifier,
  499. chunks: m.chunks,
  500. assets: m.assets,
  501. })),
  502. }),
  503. });
  504. return acc;
  505. }, [] as Array<Pick<webpack.StatsChunk, 'entry' | 'id' | 'initial' | 'files' | 'names' | 'size' | 'modules'>>);
  506. }
  507. // {
  508. // "assets": [
  509. // // A list of [asset objects](#asset-objects)
  510. // ],
  511. // "built": true, // Indicates that the module went through [Loaders](/concepts/loaders), Parsing, and Code Generation
  512. // "cacheable": true, // Whether or not this module is cacheable
  513. // "chunks": [
  514. // // IDs of chunks that contain this module
  515. // ],
  516. // "errors": 0, // Number of errors when resolving or processing the module
  517. // "failed": false, // Whether or not compilation failed on this module
  518. // "id": 0, // The ID of the module (analogous to [`module.id`](/api/module-variables/#moduleid-commonjs))
  519. // "identifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // A unique ID used internally
  520. // "name": "./lib/index.web.js", // Path to the actual file
  521. // "optional": false, // All requests to this module are with `try... catch` blocks (irrelevant with ESM)
  522. // "prefetched": false, // Indicates whether or not the module was [prefetched](/plugins/prefetch-plugin)
  523. // "profile": {
  524. // // Module specific compilation stats corresponding to the [`--profile` flag](/api/cli/#profiling) (in milliseconds)
  525. // "building": 73, // Loading and parsing
  526. // "dependencies": 242, // Building dependencies
  527. // "factory": 11 // Resolving dependencies
  528. // },
  529. // "reasons": [
  530. // {
  531. // "loc": "33:24-93", // Lines of code that caused the module to be included
  532. // "module": "./lib/index.web.js", // Relative path to the module based on [context](/configuration/entry-context/#context)
  533. // "moduleId": 0, // The ID of the module
  534. // "moduleIdentifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module
  535. // "moduleName": "./lib/index.web.js", // A more readable name for the module (used for "pretty-printing")
  536. // "type": "require.context", // The [type of request](/api/module-methods) used
  537. // "userRequest": "../../cases" // Raw string used for the `import` or `require` request
  538. // }
  539. // ],
  540. // "size": 3593, // Estimated size of the module in bytes
  541. // "source": "// Should not break it...\r\nif(typeof...", // The stringified raw source
  542. // "warnings": 0 // Number of warnings when resolving or processing the module
  543. // }
  544. if (data.modules) {
  545. finalData.modules = data.modules.reduce((acc, module) => {
  546. if (!module.name) {
  547. return acc;
  548. }
  549. acc.push({
  550. name: module.name,
  551. size: module.size,
  552. moduleType: module.moduleType,
  553. ...(module.chunks && {chunks: module.chunks}),
  554. });
  555. return acc;
  556. }, [] as Array<Pick<webpack.StatsModule, 'name' | 'chunks' | 'size' | 'moduleType'>>);
  557. }
  558. return JSON.stringify(finalData, null, 2);
  559. },
  560. }),
  561. ],
  562. resolve: {
  563. alias: {
  564. 'react-dom$': 'react-dom/profiling',
  565. 'scheduler/tracing': 'scheduler/tracing-profiling',
  566. sentry: path.join(staticPrefix, 'app'),
  567. 'sentry-images': path.join(staticPrefix, 'images'),
  568. 'sentry-logos': path.join(sentryDjangoAppPath, 'images', 'logos'),
  569. 'sentry-fonts': path.join(staticPrefix, 'fonts'),
  570. // Aliasing this for getsentry's build, otherwise `less/select2` will not be able
  571. // to be resolved
  572. less: path.join(staticPrefix, 'less'),
  573. 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
  574. 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
  575. 'ios-device-list': path.join(
  576. __dirname,
  577. 'node_modules',
  578. 'ios-device-list',
  579. 'dist',
  580. 'ios-device-list.min.js'
  581. ),
  582. },
  583. fallback: {
  584. vm: false,
  585. stream: false,
  586. crypto: require.resolve('crypto-browserify'),
  587. // `yarn why` says this is only needed in dev deps
  588. string_decoder: false,
  589. },
  590. modules: ['node_modules'],
  591. extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
  592. },
  593. output: {
  594. clean: true, // Clean the output directory before emit.
  595. path: distPath,
  596. publicPath: '',
  597. filename: 'entrypoints/[name].js',
  598. chunkFilename: 'chunks/[name].[contenthash].js',
  599. sourceMapFilename: 'sourcemaps/[name].[contenthash].js.map',
  600. assetModuleFilename: 'assets/[name].[contenthash][ext]',
  601. },
  602. optimization: {
  603. chunkIds: 'named',
  604. moduleIds: 'named',
  605. splitChunks: {
  606. // Only affect async chunks, otherwise webpack could potentially split our initial chunks
  607. // Which means the app will not load because we'd need these additional chunks to be loaded in our
  608. // django template.
  609. chunks: 'async',
  610. maxInitialRequests: 10, // (default: 30)
  611. maxAsyncRequests: 10, // (default: 30)
  612. cacheGroups: {
  613. ...localeChunkGroups,
  614. },
  615. },
  616. // This only runs in production mode
  617. // Grabbed this example from https://github.com/webpack-contrib/css-minimizer-webpack-plugin
  618. minimizer: ['...', new CssMinimizerPlugin()],
  619. },
  620. devtool: IS_PRODUCTION ? 'source-map' : 'eval-cheap-module-source-map',
  621. };
  622. if (IS_TEST || IS_ACCEPTANCE_TEST) {
  623. appConfig.resolve!.alias!['integration-docs-platforms'] = path.join(
  624. __dirname,
  625. 'fixtures/integration-docs/_platforms.json'
  626. );
  627. } else {
  628. const plugin = new IntegrationDocsFetchPlugin({basePath: __dirname});
  629. appConfig.plugins?.push(plugin);
  630. appConfig.resolve!.alias!['integration-docs-platforms'] = plugin.modulePath;
  631. }
  632. if (IS_ACCEPTANCE_TEST) {
  633. appConfig.plugins?.push(new LastBuiltPlugin({basePath: __dirname}));
  634. }
  635. // Dev only! Hot module reloading
  636. if (
  637. FORCE_WEBPACK_DEV_SERVER ||
  638. (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
  639. IS_UI_DEV_ONLY
  640. ) {
  641. if (SHOULD_HOT_MODULE_RELOAD) {
  642. // Hot reload react components on save
  643. // We include the library here as to not break docker/google cloud builds
  644. // since we do not install devDeps there.
  645. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  646. appConfig.plugins?.push(new ReactRefreshWebpackPlugin());
  647. // TODO: figure out why defining output breaks hot reloading
  648. if (IS_UI_DEV_ONLY) {
  649. appConfig.output = {};
  650. }
  651. if (SHOULD_LAZY_LOAD) {
  652. appConfig.experiments = {
  653. lazyCompilation: {
  654. // enable lazy compilation for dynamic imports
  655. imports: true,
  656. // disable lazy compilation for entries
  657. entries: false,
  658. },
  659. };
  660. }
  661. }
  662. appConfig.devServer = {
  663. headers: {
  664. 'Access-Control-Allow-Origin': '*',
  665. 'Access-Control-Allow-Credentials': 'true',
  666. 'Document-Policy': 'js-profiling',
  667. },
  668. // Cover the various environments we use (vercel, getsentry-dev, localhost)
  669. allowedHosts: [
  670. '.sentry.dev',
  671. '.dev.getsentry.net',
  672. '.localhost',
  673. '127.0.0.1',
  674. '.docker.internal',
  675. ],
  676. static: {
  677. directory: './src/sentry/static/sentry',
  678. watch: true,
  679. },
  680. host: SENTRY_WEBPACK_PROXY_HOST,
  681. // Don't reload on errors
  682. hot: 'only',
  683. port: Number(SENTRY_WEBPACK_PROXY_PORT),
  684. devMiddleware: {
  685. stats: 'errors-only',
  686. },
  687. client: {
  688. overlay: false,
  689. },
  690. };
  691. if (!IS_UI_DEV_ONLY) {
  692. // This proxies to local backend server
  693. const backendAddress = `http://127.0.0.1:${SENTRY_BACKEND_PORT}/`;
  694. const relayAddress = 'http://127.0.0.1:7899';
  695. // If we're running siloed servers we also need to proxy
  696. // those requests to the right server.
  697. let controlSiloProxy = {};
  698. if (CONTROL_SILO_PORT) {
  699. // TODO(hybridcloud) We also need to use this URL pattern
  700. // list to select contro/region when making API requests in non-proxied
  701. // environments (like production). We'll likely need a way to consolidate this
  702. // with the configuration api.Client uses.
  703. const controlSiloAddress = `http://127.0.0.1:${CONTROL_SILO_PORT}`;
  704. controlSiloProxy = {
  705. '/auth/**': controlSiloAddress,
  706. '/account/**': controlSiloAddress,
  707. '/api/0/users/**': controlSiloAddress,
  708. '/api/0/api-tokens/**': controlSiloAddress,
  709. '/api/0/sentry-apps/**': controlSiloAddress,
  710. '/api/0/organizations/*/audit-logs/**': controlSiloAddress,
  711. '/api/0/organizations/*/broadcasts/**': controlSiloAddress,
  712. '/api/0/organizations/*/integrations/**': controlSiloAddress,
  713. '/api/0/organizations/*/config/integrations/**': controlSiloAddress,
  714. '/api/0/organizations/*/sentry-apps/**': controlSiloAddress,
  715. '/api/0/organizations/*/sentry-app-installations/**': controlSiloAddress,
  716. '/api/0/api-authorizations/**': controlSiloAddress,
  717. '/api/0/api-applications/**': controlSiloAddress,
  718. '/api/0/doc-integrations/**': controlSiloAddress,
  719. '/api/0/assistant/**': controlSiloAddress,
  720. };
  721. }
  722. appConfig.devServer = {
  723. ...appConfig.devServer,
  724. static: {
  725. ...(appConfig.devServer.static as object),
  726. publicPath: '/_static/dist/sentry',
  727. },
  728. // syntax for matching is using https://www.npmjs.com/package/micromatch
  729. proxy: {
  730. ...controlSiloProxy,
  731. '/api/store/**': relayAddress,
  732. '/api/{1..9}*({0..9})/**': relayAddress,
  733. '/api/0/relays/outcomes/': relayAddress,
  734. '!/_static/dist/sentry/**': backendAddress,
  735. },
  736. };
  737. appConfig.output!.publicPath = '/_static/dist/sentry/';
  738. }
  739. }
  740. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  741. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  742. // backend (in this case, sentry.io), otherwise ALL requests are rewritten
  743. // to a development index.html -- thus, completely separating the frontend
  744. // from serving any pages through the backend.
  745. //
  746. // THIS IS EXPERIMENTAL and has limitations (e.g. you can't use SSO)
  747. //
  748. // Various sentry pages still rely on django to serve html views.
  749. if (IS_UI_DEV_ONLY) {
  750. // XXX: If you change this also change its sibiling in:
  751. // - static/index.ejs
  752. // - static/app/utils/extractSlug.tsx
  753. const KNOWN_DOMAINS =
  754. /(?:\.?)((?:localhost|dev\.getsentry\.net|sentry\.dev)(?:\:\d*)?)$/;
  755. const extractSlug = (hostname: string) => {
  756. const match = hostname.match(KNOWN_DOMAINS);
  757. if (!match) {
  758. return null;
  759. }
  760. const [
  761. matchedExpression, // Expression includes optional leading `.`
  762. ] = match;
  763. const [slug] = hostname.replace(matchedExpression, '').split('.');
  764. return slug;
  765. };
  766. // Try and load certificates from mkcert if available. Use $ yarn mkcert-localhost
  767. const certPath = path.join(__dirname, 'config');
  768. const httpsOptions = !fs.existsSync(path.join(certPath, 'localhost.pem'))
  769. ? {}
  770. : {
  771. key: fs.readFileSync(path.join(certPath, 'localhost-key.pem')),
  772. cert: fs.readFileSync(path.join(certPath, 'localhost.pem')),
  773. };
  774. appConfig.devServer = {
  775. ...appConfig.devServer,
  776. compress: true,
  777. server: {
  778. type: 'https',
  779. options: httpsOptions,
  780. },
  781. headers: {
  782. 'Document-Policy': 'js-profiling',
  783. },
  784. static: {
  785. publicPath: '/_assets/',
  786. },
  787. proxy: [
  788. {
  789. context: ['/api/', '/avatar/', '/organization-avatar/', '/extensions/'],
  790. target: 'https://sentry.io',
  791. secure: false,
  792. changeOrigin: true,
  793. headers: {
  794. Referer: 'https://sentry.io/',
  795. 'Document-Policy': 'js-profiling',
  796. },
  797. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  798. router: ({hostname}) => {
  799. const orgSlug = extractSlug(hostname);
  800. return orgSlug ? `https://${orgSlug}.sentry.io` : 'https://sentry.io';
  801. },
  802. },
  803. ],
  804. historyApiFallback: {
  805. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  806. },
  807. };
  808. appConfig.optimization = {
  809. runtimeChunk: 'single',
  810. };
  811. }
  812. if (IS_UI_DEV_ONLY || SENTRY_EXPERIMENTAL_SPA) {
  813. appConfig.output!.publicPath = '/_assets/';
  814. /**
  815. * Generate a index.html file used for running the app in pure client mode.
  816. * This is currently used for PR deploy previews, where only the frontend
  817. * is deployed.
  818. */
  819. const HtmlWebpackPlugin = require('html-webpack-plugin');
  820. appConfig.plugins?.push(
  821. new HtmlWebpackPlugin({
  822. // Local dev vs vercel slightly differs...
  823. ...(IS_UI_DEV_ONLY
  824. ? {devServer: `https://127.0.0.1:${SENTRY_WEBPACK_PROXY_PORT}`}
  825. : {}),
  826. favicon: path.resolve(sentryDjangoAppPath, 'images', 'favicon_dev.png'),
  827. template: path.resolve(staticPrefix, 'index.ejs'),
  828. mobile: true,
  829. excludeChunks: ['pipeline'],
  830. title: 'Sentry',
  831. window: {
  832. __SENTRY_DEV_UI: true,
  833. },
  834. })
  835. );
  836. }
  837. const minificationPlugins = [
  838. // This compression-webpack-plugin generates pre-compressed files
  839. // ending in .gz, to be picked up and served by our internal static media
  840. // server as well as nginx when paired with the gzip_static module.
  841. //
  842. // TODO(ts): The current @types/compression-webpack-plugin is still targeting
  843. // webpack@4, for now we just as any it.
  844. new CompressionPlugin({
  845. algorithm: 'gzip',
  846. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  847. }) as any,
  848. // NOTE: In production mode webpack will automatically minify javascript
  849. // using the TerserWebpackPlugin.
  850. ];
  851. if (IS_PRODUCTION) {
  852. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  853. minificationPlugins.forEach(plugin => appConfig.plugins?.push(plugin));
  854. }
  855. // Cache webpack builds
  856. if (env.WEBPACK_CACHE_PATH) {
  857. appConfig.cache = {
  858. type: 'filesystem',
  859. cacheLocation: path.resolve(__dirname, env.WEBPACK_CACHE_PATH),
  860. buildDependencies: {
  861. // This makes all dependencies of this file - build dependencies
  862. config: [__filename],
  863. // By default webpack and loaders are build dependencies
  864. },
  865. };
  866. }
  867. export default appConfig;