webpack.config.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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.PULL_REQUEST && {
  49. commitRef: env.COMMIT_REF,
  50. reviewId: env.REVIEW_ID,
  51. repoUrl: env.REPOSITORY_URL,
  52. };
  53. // When deploy previews are enabled always enable experimental SPA mode --
  54. // deploy previews are served standalone. Otherwise fallback to the environment
  55. // configuration.
  56. const SENTRY_EXPERIMENTAL_SPA = !DEPLOY_PREVIEW_CONFIG
  57. ? env.SENTRY_EXPERIMENTAL_SPA
  58. : 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. '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. const tsLoaderConfig = {
  186. loader: 'ts-loader',
  187. };
  188. /**
  189. * Main Webpack config for Sentry React SPA.
  190. */
  191. let appConfig = {
  192. mode: WEBPACK_MODE,
  193. entry: {
  194. /**
  195. * Main Sentry SPA
  196. */
  197. app: 'app',
  198. /**
  199. * Legacy CSS Webpack appConfig for Django-powered views.
  200. * This generates a single "sentry.css" file that imports ALL component styles
  201. * for use on Django-powered pages.
  202. */
  203. sentry: 'less/sentry.less',
  204. /**
  205. * old plugins that use select2 when creating a new issue e.g. Trello, Teamwork*
  206. */
  207. select2: 'less/select2.less',
  208. },
  209. context: staticPrefix,
  210. module: {
  211. rules: [
  212. {
  213. test: /\.jsx?$/,
  214. include: [staticPrefix],
  215. exclude: /(vendor|node_modules|dist)/,
  216. use: babelLoaderConfig,
  217. },
  218. {
  219. test: /\.tsx?$/,
  220. include: [staticPrefix],
  221. exclude: /(vendor|node_modules|dist)/,
  222. // Make sure we typecheck in CI, but not for local dev since that is run with
  223. // the fork-ts plugin
  224. use: SHOULD_FORK_TS ? babelLoaderConfig : [babelLoaderConfig, tsLoaderConfig],
  225. },
  226. {
  227. test: /\.po$/,
  228. use: {
  229. loader: 'po-catalog-loader',
  230. options: {
  231. referenceExtensions: ['.js', '.jsx'],
  232. domain: 'sentry',
  233. },
  234. },
  235. },
  236. {
  237. test: /app\/icons\/.*\.svg$/,
  238. use: ['svg-sprite-loader', 'svgo-loader'],
  239. },
  240. {
  241. test: /\.css/,
  242. use: ['style-loader', 'css-loader'],
  243. },
  244. {
  245. test: /\.less$/,
  246. include: [staticPrefix],
  247. use: [ExtractTextPlugin.loader, 'css-loader', 'less-loader'],
  248. },
  249. {
  250. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  251. exclude: /app\/icons\/.*\.svg$/,
  252. use: [
  253. {
  254. loader: 'file-loader',
  255. options: {
  256. name: '[name].[hash:6].[ext]',
  257. },
  258. },
  259. ],
  260. },
  261. ],
  262. noParse: [
  263. // don't parse known, pre-built javascript files (improves webpack perf)
  264. /dist\/jquery\.js/,
  265. /jed\/jed\.js/,
  266. /marked\/lib\/marked\.js/,
  267. /terser\/dist\/bundle\.min\.js/,
  268. ],
  269. },
  270. plugins: [
  271. new CleanWebpackPlugin(),
  272. /**
  273. * jQuery must be provided in the global scope specifically and only for
  274. * bootstrap, as it will not import jQuery itself.
  275. *
  276. * We discourage the use of global jQuery through eslint rules
  277. */
  278. new webpack.ProvidePlugin({jQuery: 'jquery'}),
  279. /**
  280. * Extract CSS into separate files.
  281. */
  282. new ExtractTextPlugin(),
  283. /**
  284. * Defines environment specific flags.
  285. */
  286. new webpack.DefinePlugin({
  287. 'process.env': {
  288. NODE_ENV: JSON.stringify(env.NODE_ENV),
  289. IS_PERCY: JSON.stringify(IS_PERCY),
  290. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  291. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  292. },
  293. }),
  294. /**
  295. * See above for locale chunks. These plugins help with that
  296. * functionality.
  297. */
  298. new OptionalLocaleChunkPlugin(),
  299. /**
  300. * This removes empty js files for style only entries (e.g. sentry.less)
  301. */
  302. new FixStyleOnlyEntriesPlugin(),
  303. new SentryInstrumentation(),
  304. ...(SHOULD_FORK_TS
  305. ? [
  306. new ForkTsCheckerWebpackPlugin({
  307. eslint: TS_FORK_WITH_ESLINT,
  308. tsconfig: path.resolve(__dirname, './tsconfig.json'),
  309. }),
  310. ]
  311. : []),
  312. ...localeRestrictionPlugins,
  313. ],
  314. resolve: {
  315. alias: {
  316. app: path.join(staticPrefix, 'app'),
  317. '@emotion/styled': path.join(staticPrefix, 'app', 'styled'),
  318. '@original-emotion/styled': path.join(
  319. __dirname,
  320. 'node_modules',
  321. '@emotion',
  322. 'styled'
  323. ),
  324. // Aliasing this for getsentry's build, otherwise `less/select2` will not be able
  325. // to be resolved
  326. less: path.join(staticPrefix, 'less'),
  327. 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
  328. 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
  329. },
  330. modules: ['node_modules'],
  331. extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
  332. },
  333. output: {
  334. path: distPath,
  335. filename: '[name].js',
  336. // Rename global that is used to async load chunks
  337. // Avoids 3rd party js from overwriting the default name (webpackJsonp)
  338. jsonpFunction: 'sntryWpJsonp',
  339. sourceMapFilename: '[name].js.map',
  340. },
  341. optimization: {
  342. splitChunks: {
  343. chunks: 'all',
  344. maxInitialRequests: 5,
  345. maxAsyncRequests: 7,
  346. cacheGroups,
  347. },
  348. },
  349. devtool: IS_PRODUCTION ? 'source-map' : 'cheap-module-eval-source-map',
  350. };
  351. if (SENTRY_EXPERIMENTAL_SPA) {
  352. /**
  353. * Generate a index.html file used for running the app in pure client mode.
  354. * This is currently used for PR deploy previews, where only the frontend
  355. * is deployed.
  356. */
  357. appConfig.plugins.push(
  358. new CopyPlugin([{from: path.join(staticPrefix, 'app', 'index.html')}])
  359. );
  360. }
  361. if (IS_TEST || IS_STORYBOOK) {
  362. appConfig.resolve.alias['integration-docs-platforms'] = path.join(
  363. __dirname,
  364. 'tests/fixtures/integration-docs/_platforms.json'
  365. );
  366. } else {
  367. const plugin = new IntegrationDocsFetchPlugin({basePath: __dirname});
  368. appConfig.plugins.push(plugin);
  369. appConfig.resolve.alias['integration-docs-platforms'] = plugin.modulePath;
  370. }
  371. if (!IS_PRODUCTION) {
  372. appConfig.plugins.push(new LastBuiltPlugin({basePath: __dirname}));
  373. }
  374. // Dev only! Hot module reloading
  375. if (FORCE_WEBPACK_DEV_SERVER || (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER)) {
  376. const backendAddress = `http://localhost:${SENTRY_BACKEND_PORT}/`;
  377. if (SHOULD_HOT_MODULE_RELOAD) {
  378. // Hot reload react components on save
  379. // We include the library here as to not break docker/google cloud builds
  380. // since we do not install devDeps there.
  381. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  382. appConfig.plugins.push(new ReactRefreshWebpackPlugin());
  383. }
  384. appConfig.devServer = {
  385. headers: {
  386. 'Access-Control-Allow-Origin': '*',
  387. 'Access-Control-Allow-Credentials': 'true',
  388. },
  389. // Required for getsentry
  390. disableHostCheck: true,
  391. contentBase: './src/sentry/static/sentry',
  392. hot: true,
  393. // If below is false, will reload on errors
  394. hotOnly: true,
  395. port: SENTRY_WEBPACK_PROXY_PORT,
  396. stats: 'errors-only',
  397. overlay: false,
  398. watchOptions: {
  399. ignored: ['node_modules'],
  400. },
  401. publicPath: '/_webpack',
  402. proxy: {'!/_webpack': backendAddress},
  403. before: app =>
  404. app.use((req, _res, next) => {
  405. req.url = req.url.replace(/^\/_static\/[^\/]+\/sentry\/dist/, '/_webpack');
  406. next();
  407. }),
  408. };
  409. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  410. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  411. // backend, otherwise ALL requests are rewritten to a development index.html.
  412. // Thus completely separating the frontend from serving any pages through the
  413. // backend.
  414. //
  415. // THIS IS EXPERIMENTAL. Various sentry pages still rely on django to serve
  416. // html views.
  417. appConfig.devServer = !SENTRY_EXPERIMENTAL_SPA
  418. ? appConfig.devServer
  419. : {
  420. ...appConfig.devServer,
  421. before: () => undefined,
  422. publicPath: '/_assets',
  423. proxy: {'/api/': backendAddress},
  424. historyApiFallback: {
  425. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  426. },
  427. };
  428. }
  429. const minificationPlugins = [
  430. // This compression-webpack-plugin generates pre-compressed files
  431. // ending in .gz, to be picked up and served by our internal static media
  432. // server as well as nginx when paired with the gzip_static module.
  433. new CompressionPlugin({
  434. algorithm: 'gzip',
  435. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  436. }),
  437. new OptimizeCssAssetsPlugin(),
  438. // NOTE: In production mode webpack will automatically minify javascript
  439. // using the TerserWebpackPlugin.
  440. ];
  441. if (IS_PRODUCTION) {
  442. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  443. minificationPlugins.forEach(function(plugin) {
  444. appConfig.plugins.push(plugin);
  445. });
  446. }
  447. if (env.MEASURE) {
  448. const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
  449. const smp = new SpeedMeasurePlugin();
  450. appConfig = smp.wrap(appConfig);
  451. }
  452. module.exports = appConfig;