webpack.config.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 ExtractTextPlugin = require('mini-css-extract-plugin');
  8. const CompressionPlugin = require('compression-webpack-plugin');
  9. const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  10. const FixStyleOnlyEntriesPlugin = require('webpack-fix-style-only-entries');
  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 =>
  145. localeGroupTests.some(pattern =>
  146. module.nameForCondition && pattern.test(module.nameForCondition())
  147. ? true
  148. : Array.from(module.chunksIterable).some(c => c.name && pattern.test(c.name))
  149. );
  150. localeChunkGroups[group] = {
  151. name: group,
  152. test: groupTest,
  153. enforce: true,
  154. };
  155. });
  156. /**
  157. * Restrict translation files that are pulled in through app/translations.jsx
  158. * and through moment/locale/* to only those which we create bundles for via
  159. * locale/catalogs.json.
  160. */
  161. const localeRestrictionPlugins = [
  162. new webpack.ContextReplacementPlugin(
  163. /sentry-locale$/,
  164. path.join(__dirname, 'src', 'sentry', 'locale', path.sep),
  165. true,
  166. new RegExp(`(${supportedLocales.join('|')})/.*\\.po$`)
  167. ),
  168. new webpack.ContextReplacementPlugin(
  169. /moment\/locale/,
  170. new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
  171. ),
  172. ];
  173. /**
  174. * Explicit codesplitting cache groups
  175. */
  176. const cacheGroups = {
  177. vendors: {
  178. name: 'vendor',
  179. // This `platformicons` check is required otherwise it will get put into this chunk instead
  180. // of `sentry.css` bundle
  181. // TODO(platformicons): Simplify this if we move platformicons into repo
  182. test: module =>
  183. !/platformicons/.test(module.resource) &&
  184. /[\\/]node_modules[\\/]/.test(module.resource),
  185. priority: -10,
  186. enforce: true,
  187. chunks: 'initial',
  188. },
  189. ...localeChunkGroups,
  190. };
  191. const babelOptions = {...babelConfig, cacheDirectory: true};
  192. const babelLoaderConfig = {
  193. loader: 'babel-loader',
  194. options: babelOptions,
  195. };
  196. /**
  197. * Main Webpack config for Sentry React SPA.
  198. */
  199. let appConfig = {
  200. mode: WEBPACK_MODE,
  201. entry: {
  202. /**
  203. * Main Sentry SPA
  204. */
  205. app: 'app',
  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. * Old plugins that use select2 when creating a new issue e.g. Trello, Teamwork*
  214. */
  215. select2: 'less/select2.less',
  216. },
  217. context: staticPrefix,
  218. module: {
  219. /**
  220. * XXX: Modifying the order/contents of these rules may break `getsentry`
  221. * Please remember to test it.
  222. */
  223. rules: [
  224. {
  225. test: /\.[tj]sx?$/,
  226. include: [staticPrefix],
  227. exclude: /(vendor|node_modules|dist)/,
  228. use: babelLoaderConfig,
  229. },
  230. {
  231. test: /\.po$/,
  232. use: {
  233. loader: 'po-catalog-loader',
  234. options: {
  235. referenceExtensions: ['.js', '.jsx'],
  236. domain: 'sentry',
  237. },
  238. },
  239. },
  240. {
  241. test: /\.css/,
  242. use: ['style-loader', 'css-loader'],
  243. },
  244. {
  245. test: /\.less$/,
  246. include: [staticPrefix],
  247. use: [ExtractTextPlugin.loader, 'css-loader', 'less-loader'],
  248. },
  249. {
  250. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  251. use: [
  252. {
  253. loader: 'file-loader',
  254. options: {
  255. // This needs to be `false` because of platformicons package
  256. esModule: false,
  257. name: '[folder]/[name].[hash:6].[ext]',
  258. },
  259. },
  260. ],
  261. },
  262. ],
  263. noParse: [
  264. // don't parse known, pre-built javascript files (improves webpack perf)
  265. /dist\/jquery\.js/,
  266. /jed\/jed\.js/,
  267. /marked\/lib\/marked\.js/,
  268. /terser\/dist\/bundle\.min\.js/,
  269. ],
  270. },
  271. plugins: [
  272. new CleanWebpackPlugin(),
  273. /**
  274. * jQuery must be provided in the global scope specifically and only for
  275. * bootstrap, as it will not import jQuery itself.
  276. *
  277. * We discourage the use of global jQuery through eslint rules
  278. */
  279. new webpack.ProvidePlugin({jQuery: 'jquery'}),
  280. /**
  281. * Extract CSS into separate files.
  282. */
  283. new ExtractTextPlugin(),
  284. /**
  285. * Defines environment specific flags.
  286. */
  287. new webpack.DefinePlugin({
  288. 'process.env': {
  289. NODE_ENV: JSON.stringify(env.NODE_ENV),
  290. IS_ACCEPTANCE_TEST: JSON.stringify(IS_ACCEPTANCE_TEST),
  291. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  292. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  293. SPA_DSN: JSON.stringify(env.SENTRY_SPA_DSN),
  294. },
  295. }),
  296. /**
  297. * See above for locale chunks. These plugins help with that
  298. * functionality.
  299. */
  300. new OptionalLocaleChunkPlugin(),
  301. /**
  302. * This removes empty js files for style only entries (e.g. sentry.less)
  303. */
  304. new FixStyleOnlyEntriesPlugin({silent: true}),
  305. new SentryInstrumentation(),
  306. ...(SHOULD_FORK_TS
  307. ? [
  308. new ForkTsCheckerWebpackPlugin({
  309. eslint: TS_FORK_WITH_ESLINT,
  310. tsconfig: path.resolve(__dirname, './config/tsconfig.build.json'),
  311. }),
  312. ]
  313. : []),
  314. ...localeRestrictionPlugins,
  315. ],
  316. resolve: {
  317. alias: {
  318. app: path.join(staticPrefix, 'app'),
  319. 'sentry-images': path.join(staticPrefix, 'images'),
  320. 'sentry-fonts': path.join(staticPrefix, 'fonts'),
  321. '@emotion/styled': path.join(staticPrefix, 'app', 'styled'),
  322. '@original-emotion/styled': path.join(
  323. __dirname,
  324. 'node_modules',
  325. '@emotion',
  326. 'styled'
  327. ),
  328. // Aliasing this for getsentry's build, otherwise `less/select2` will not be able
  329. // to be resolved
  330. less: path.join(staticPrefix, 'less'),
  331. 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
  332. 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
  333. 'ios-device-list': path.join(
  334. __dirname,
  335. 'node_modules',
  336. 'ios-device-list',
  337. 'dist',
  338. 'ios-device-list.min.js'
  339. ),
  340. },
  341. modules: ['node_modules'],
  342. extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
  343. },
  344. output: {
  345. path: distPath,
  346. filename: '[name].js',
  347. // Rename global that is used to async load chunks
  348. // Avoids 3rd party js from overwriting the default name (webpackJsonp)
  349. jsonpFunction: 'sntryWpJsonp',
  350. sourceMapFilename: '[name].js.map',
  351. },
  352. optimization: {
  353. splitChunks: {
  354. chunks: 'all',
  355. maxInitialRequests: 5,
  356. maxAsyncRequests: 7,
  357. cacheGroups,
  358. },
  359. },
  360. devtool: IS_PRODUCTION ? 'source-map' : 'cheap-module-eval-source-map',
  361. };
  362. if (IS_TEST || IS_ACCEPTANCE_TEST || IS_STORYBOOK) {
  363. appConfig.resolve.alias['integration-docs-platforms'] = path.join(
  364. __dirname,
  365. 'tests/fixtures/integration-docs/_platforms.json'
  366. );
  367. } else {
  368. const plugin = new IntegrationDocsFetchPlugin({basePath: __dirname});
  369. appConfig.plugins.push(plugin);
  370. appConfig.resolve.alias['integration-docs-platforms'] = plugin.modulePath;
  371. }
  372. if (IS_ACCEPTANCE_TEST) {
  373. appConfig.plugins.push(new LastBuiltPlugin({basePath: __dirname}));
  374. }
  375. // Dev only! Hot module reloading
  376. if (
  377. FORCE_WEBPACK_DEV_SERVER ||
  378. (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
  379. IS_UI_DEV_ONLY
  380. ) {
  381. if (SHOULD_HOT_MODULE_RELOAD) {
  382. // Hot reload react components on save
  383. // We include the library here as to not break docker/google cloud builds
  384. // since we do not install devDeps there.
  385. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  386. appConfig.plugins.push(new ReactRefreshWebpackPlugin());
  387. }
  388. appConfig.devServer = {
  389. headers: {
  390. 'Access-Control-Allow-Origin': '*',
  391. 'Access-Control-Allow-Credentials': 'true',
  392. },
  393. // Required for getsentry
  394. disableHostCheck: true,
  395. contentBase: './src/sentry/static/sentry',
  396. host: SENTRY_WEBPACK_PROXY_HOST,
  397. hot: true,
  398. // If below is false, will reload on errors
  399. hotOnly: true,
  400. port: SENTRY_WEBPACK_PROXY_PORT,
  401. stats: 'errors-only',
  402. overlay: false,
  403. watchOptions: {
  404. ignored: ['node_modules'],
  405. },
  406. };
  407. if (!IS_UI_DEV_ONLY) {
  408. // This proxies to local backend server
  409. const backendAddress = `http://localhost:${SENTRY_BACKEND_PORT}/`;
  410. const relayAddress = 'http://127.0.0.1:7899';
  411. appConfig.devServer = {
  412. ...appConfig.devServer,
  413. publicPath: '/_webpack',
  414. // syntax for matching is using https://www.npmjs.com/package/micromatch
  415. proxy: {
  416. '/api/store/**': relayAddress,
  417. '/api/{1..9}*({0..9})/**': relayAddress,
  418. '/api/0/relays/outcomes/': relayAddress,
  419. '!/_webpack': backendAddress,
  420. },
  421. before: app =>
  422. app.use((req, _res, next) => {
  423. req.url = req.url.replace(/^\/_static\/[^\/]+\/sentry\/dist/, '/_webpack');
  424. next();
  425. }),
  426. };
  427. }
  428. }
  429. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  430. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  431. // backend (in this case, sentry.io), otherwise ALL requests are rewritten
  432. // to a development index.html -- thus, completely separating the frontend
  433. // from serving any pages through the backend.
  434. //
  435. // THIS IS EXPERIMENTAL and has limitations (e.g. you can't use SSO)
  436. //
  437. // Various sentry pages still rely on django to serve html views.
  438. if (IS_UI_DEV_ONLY) {
  439. appConfig.devServer = {
  440. ...appConfig.devServer,
  441. compress: true,
  442. https: true,
  443. publicPath: '/_assets/',
  444. proxy: [
  445. {
  446. context: ['/api/', '/avatar/', '/organization-avatar/'],
  447. target: 'https://sentry.io',
  448. secure: false,
  449. changeOrigin: true,
  450. headers: {
  451. Referer: 'https://sentry.io/',
  452. },
  453. },
  454. ],
  455. historyApiFallback: {
  456. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  457. },
  458. };
  459. }
  460. if (IS_UI_DEV_ONLY || IS_DEPLOY_PREVIEW) {
  461. appConfig.output.publicPath = '/_assets/';
  462. /**
  463. * Generate a index.html file used for running the app in pure client mode.
  464. * This is currently used for PR deploy previews, where only the frontend
  465. * is deployed.
  466. */
  467. const HtmlWebpackPlugin = require('html-webpack-plugin');
  468. appConfig.plugins.push(
  469. new HtmlWebpackPlugin({
  470. // Local dev vs vercel slightly differs...
  471. ...(IS_UI_DEV_ONLY
  472. ? {devServer: `https://localhost:${SENTRY_WEBPACK_PROXY_PORT}`}
  473. : {}),
  474. favicon: path.resolve(staticPrefix, 'images', 'favicon_dev.png'),
  475. template: path.resolve(staticPrefix, 'index.ejs'),
  476. mobile: true,
  477. title: 'Sentry',
  478. })
  479. );
  480. }
  481. const minificationPlugins = [
  482. // This compression-webpack-plugin generates pre-compressed files
  483. // ending in .gz, to be picked up and served by our internal static media
  484. // server as well as nginx when paired with the gzip_static module.
  485. new CompressionPlugin({
  486. algorithm: 'gzip',
  487. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  488. }),
  489. new OptimizeCssAssetsPlugin(),
  490. // NOTE: In production mode webpack will automatically minify javascript
  491. // using the TerserWebpackPlugin.
  492. ];
  493. if (IS_PRODUCTION) {
  494. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  495. minificationPlugins.forEach(function (plugin) {
  496. appConfig.plugins.push(plugin);
  497. });
  498. }
  499. if (env.MEASURE) {
  500. const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
  501. const smp = new SpeedMeasurePlugin();
  502. appConfig = smp.wrap(appConfig);
  503. }
  504. module.exports = appConfig;