webpack.config.js 15 KB

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