webpack.config.js 14 KB

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