webpack.config.js 16 KB

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