webpack.config.js 17 KB

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