webpack.config.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 CopyPlugin = require('copy-webpack-plugin');
  12. const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
  13. const IntegrationDocsFetchPlugin = require('./build-utils/integration-docs-fetch-plugin');
  14. const OptionalLocaleChunkPlugin = require('./build-utils/optional-locale-chunk-plugin');
  15. const SentryInstrumentation = require('./build-utils/sentry-instrumentation');
  16. const LastBuiltPlugin = require('./build-utils/last-built-plugin');
  17. const babelConfig = require('./babel.config');
  18. const {env} = process;
  19. /**
  20. * Environment configuration
  21. */
  22. const IS_PRODUCTION = env.NODE_ENV === 'production';
  23. const IS_TEST = env.NODE_ENV === 'test' || env.TEST_SUITE;
  24. const IS_STORYBOOK = env.STORYBOOK_BUILD === '1';
  25. const IS_CI = !!env.CI || !!env.TRAVIS;
  26. const IS_PERCY = env.CI && !!env.PERCY_TOKEN && !!env.TRAVIS;
  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 enviroment 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 = env.NOW_GITHUB_DEPLOYMENT && {
  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 = !DEPLOY_PREVIEW_CONFIG
  58. ? env.SENTRY_EXPERIMENTAL_SPA
  59. : 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. '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. const tsLoaderConfig = {
  187. loader: 'ts-loader',
  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. rules: [
  213. {
  214. test: /\.jsx?$/,
  215. include: [staticPrefix],
  216. exclude: /(vendor|node_modules|dist)/,
  217. use: babelLoaderConfig,
  218. },
  219. {
  220. test: /\.tsx?$/,
  221. include: [staticPrefix],
  222. exclude: /(vendor|node_modules|dist)/,
  223. // Make sure we typecheck in CI, but not for local dev since that is run with
  224. // the fork-ts plugin
  225. use: SHOULD_FORK_TS ? babelLoaderConfig : [babelLoaderConfig, tsLoaderConfig],
  226. },
  227. {
  228. test: /\.po$/,
  229. use: {
  230. loader: 'po-catalog-loader',
  231. options: {
  232. referenceExtensions: ['.js', '.jsx'],
  233. domain: 'sentry',
  234. },
  235. },
  236. },
  237. {
  238. test: /app\/icons\/.*\.svg$/,
  239. use: ['svg-sprite-loader', 'svgo-loader'],
  240. },
  241. {
  242. test: /\.css/,
  243. use: ['style-loader', 'css-loader'],
  244. },
  245. {
  246. test: /\.less$/,
  247. include: [staticPrefix],
  248. use: [ExtractTextPlugin.loader, 'css-loader', 'less-loader'],
  249. },
  250. {
  251. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  252. exclude: /app\/icons\/.*\.svg$/,
  253. use: [
  254. {
  255. loader: 'file-loader',
  256. options: {
  257. name: '[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_PERCY: JSON.stringify(IS_PERCY),
  291. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  292. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  293. },
  294. }),
  295. /**
  296. * See above for locale chunks. These plugins help with that
  297. * functionality.
  298. */
  299. new OptionalLocaleChunkPlugin(),
  300. /**
  301. * This removes empty js files for style only entries (e.g. sentry.less)
  302. */
  303. new FixStyleOnlyEntriesPlugin(),
  304. new SentryInstrumentation(),
  305. ...(SHOULD_FORK_TS
  306. ? [
  307. new ForkTsCheckerWebpackPlugin({
  308. eslint: TS_FORK_WITH_ESLINT,
  309. tsconfig: path.resolve(__dirname, './tsconfig.json'),
  310. }),
  311. ]
  312. : []),
  313. ...localeRestrictionPlugins,
  314. ],
  315. resolve: {
  316. alias: {
  317. app: path.join(staticPrefix, 'app'),
  318. '@emotion/styled': path.join(staticPrefix, 'app', 'styled'),
  319. '@original-emotion/styled': path.join(
  320. __dirname,
  321. 'node_modules',
  322. '@emotion',
  323. 'styled'
  324. ),
  325. // Aliasing this for getsentry's build, otherwise `less/select2` will not be able
  326. // to be resolved
  327. less: path.join(staticPrefix, 'less'),
  328. 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
  329. 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
  330. },
  331. modules: ['node_modules'],
  332. extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
  333. },
  334. output: {
  335. path: distPath,
  336. filename: '[name].js',
  337. // Rename global that is used to async load chunks
  338. // Avoids 3rd party js from overwriting the default name (webpackJsonp)
  339. jsonpFunction: 'sntryWpJsonp',
  340. sourceMapFilename: '[name].js.map',
  341. },
  342. optimization: {
  343. splitChunks: {
  344. chunks: 'all',
  345. maxInitialRequests: 5,
  346. maxAsyncRequests: 7,
  347. cacheGroups,
  348. },
  349. },
  350. devtool: IS_PRODUCTION ? 'source-map' : 'cheap-module-eval-source-map',
  351. };
  352. if (SENTRY_EXPERIMENTAL_SPA) {
  353. /**
  354. * Generate a index.html file used for running the app in pure client mode.
  355. * This is currently used for PR deploy previews, where only the frontend
  356. * is deployed.
  357. */
  358. appConfig.plugins.push(
  359. new CopyPlugin([{from: path.join(staticPrefix, 'app', 'index.html')}])
  360. );
  361. }
  362. if (IS_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_PRODUCTION) {
  373. appConfig.plugins.push(new LastBuiltPlugin({basePath: __dirname}));
  374. }
  375. // Dev only! Hot module reloading
  376. if (FORCE_WEBPACK_DEV_SERVER || (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER)) {
  377. const backendAddress = `http://localhost:${SENTRY_BACKEND_PORT}/`;
  378. if (SHOULD_HOT_MODULE_RELOAD) {
  379. // Hot reload react components on save
  380. // We include the library here as to not break docker/google cloud builds
  381. // since we do not install devDeps there.
  382. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  383. appConfig.plugins.push(new ReactRefreshWebpackPlugin());
  384. }
  385. appConfig.devServer = {
  386. headers: {
  387. 'Access-Control-Allow-Origin': '*',
  388. 'Access-Control-Allow-Credentials': 'true',
  389. },
  390. // Required for getsentry
  391. disableHostCheck: true,
  392. contentBase: './src/sentry/static/sentry',
  393. hot: true,
  394. // If below is false, will reload on errors
  395. hotOnly: true,
  396. port: SENTRY_WEBPACK_PROXY_PORT,
  397. stats: 'errors-only',
  398. overlay: false,
  399. watchOptions: {
  400. ignored: ['node_modules'],
  401. },
  402. publicPath: '/_webpack',
  403. proxy: {'!/_webpack': backendAddress},
  404. before: app =>
  405. app.use((req, _res, next) => {
  406. req.url = req.url.replace(/^\/_static\/[^\/]+\/sentry\/dist/, '/_webpack');
  407. next();
  408. }),
  409. };
  410. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  411. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  412. // backend, otherwise ALL requests are rewritten to a development index.html.
  413. // Thus completely separating the frontend from serving any pages through the
  414. // backend.
  415. //
  416. // THIS IS EXPERIMENTAL. Various sentry pages still rely on django to serve
  417. // html views.
  418. appConfig.devServer = !SENTRY_EXPERIMENTAL_SPA
  419. ? appConfig.devServer
  420. : {
  421. ...appConfig.devServer,
  422. before: () => undefined,
  423. publicPath: '/_assets',
  424. proxy: {'/api/': backendAddress},
  425. historyApiFallback: {
  426. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  427. },
  428. };
  429. }
  430. const minificationPlugins = [
  431. // This compression-webpack-plugin generates pre-compressed files
  432. // ending in .gz, to be picked up and served by our internal static media
  433. // server as well as nginx when paired with the gzip_static module.
  434. new CompressionPlugin({
  435. algorithm: 'gzip',
  436. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  437. }),
  438. new OptimizeCssAssetsPlugin(),
  439. // NOTE: In production mode webpack will automatically minify javascript
  440. // using the TerserWebpackPlugin.
  441. ];
  442. if (IS_PRODUCTION) {
  443. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  444. minificationPlugins.forEach(function(plugin) {
  445. appConfig.plugins.push(plugin);
  446. });
  447. }
  448. if (env.MEASURE) {
  449. const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
  450. const smp = new SpeedMeasurePlugin();
  451. appConfig = smp.wrap(appConfig);
  452. }
  453. module.exports = appConfig;