webpack.config.js 16 KB

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