webpack.config.js 18 KB

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