webpack.config.js 17 KB

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