webpack.config.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 OptionalLocaleChunkPlugin = require('./build-utils/optional-locale-chunk-plugin');
  9. const IntegrationDocsFetchPlugin = require('./build-utils/integration-docs-fetch-plugin');
  10. const ExtractTextPlugin = require('mini-css-extract-plugin');
  11. const CompressionPlugin = require('compression-webpack-plugin');
  12. const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  13. const LodashModuleReplacementPlugin = require('lodash-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. const 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. },
  210. ],
  211. },
  212. {
  213. test: /\.po$/,
  214. use: {
  215. loader: 'po-catalog-loader',
  216. options: {
  217. referenceExtensions: ['.js', '.jsx'],
  218. domain: 'sentry',
  219. },
  220. },
  221. },
  222. {
  223. test: /app\/icons\/.*\.svg$/,
  224. use: ['svg-sprite-loader', 'svgo-loader'],
  225. },
  226. {
  227. test: /\.css/,
  228. use: ['style-loader', 'css-loader'],
  229. },
  230. {
  231. test: /\.less$/,
  232. include: [staticPrefix],
  233. use: [ExtractTextPlugin.loader, 'css-loader', 'less-loader'],
  234. },
  235. {
  236. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg)($|\?)/,
  237. exclude: /app\/icons\/.*\.svg$/,
  238. use: [
  239. {
  240. loader: 'file-loader',
  241. options: {
  242. name: '[name].[ext]',
  243. },
  244. },
  245. ],
  246. },
  247. ],
  248. noParse: [
  249. // don't parse known, pre-built javascript files (improves webpack perf)
  250. /dist\/jquery\.js/,
  251. /jed\/jed\.js/,
  252. /marked\/lib\/marked\.js/,
  253. ],
  254. },
  255. plugins: [
  256. new CleanWebpackPlugin(),
  257. /**
  258. * Used to make our lodash modules even smaller
  259. */
  260. new LodashModuleReplacementPlugin({
  261. collections: true,
  262. currying: true, // these are enabled to support lodash/fp/ features
  263. flattening: true, // used by a dependency of react-mentions
  264. shorthands: true,
  265. paths: true,
  266. exotics: true,
  267. }),
  268. /**
  269. * jQuery must be provided in the global scope specifically and only for
  270. * bootstrap, as it will not import jQuery itself.
  271. *
  272. * We discourage the use of global jQuery through eslint rules
  273. */
  274. new webpack.ProvidePlugin({jQuery: 'jquery'}),
  275. /**
  276. * Extract CSS into separate files.
  277. */
  278. new ExtractTextPlugin(),
  279. /**
  280. * Generate a index.html file used for running the app in pure client mode.
  281. * This is currently used for PR deploy previews, where only the frontend
  282. * is deployed.
  283. */
  284. new CopyPlugin([{from: path.join(staticPrefix, 'app', 'index.html')}]),
  285. /**
  286. * Defines environment specific flags.
  287. */
  288. new webpack.DefinePlugin({
  289. 'process.env': {
  290. NODE_ENV: JSON.stringify(env.NODE_ENV),
  291. IS_PERCY: JSON.stringify(env.CI && !!env.PERCY_TOKEN && !!env.TRAVIS),
  292. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  293. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  294. },
  295. }),
  296. /**
  297. * See above for locale chunks. These plugins help with that
  298. * functionality.
  299. */
  300. new OptionalLocaleChunkPlugin(),
  301. /**
  302. * This removes empty js files for style only entries (e.g. sentry.less)
  303. */
  304. new FixStyleOnlyEntriesPlugin(),
  305. ...localeRestrictionPlugins,
  306. ],
  307. resolve: {
  308. alias: {
  309. app: path.join(staticPrefix, 'app'),
  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 (IS_TEST || IS_STORYBOOK) {
  338. appConfig.resolve.alias['integration-docs-platforms'] = path.join(
  339. __dirname,
  340. 'tests/fixtures/integration-docs/_platforms.json'
  341. );
  342. } else {
  343. const plugin = new IntegrationDocsFetchPlugin({basePath: __dirname});
  344. appConfig.plugins.push(plugin);
  345. appConfig.resolve.alias['integration-docs-platforms'] = plugin.modulePath;
  346. }
  347. if (!IS_PRODUCTION) {
  348. appConfig.plugins.push(new LastBuiltPlugin({basePath: __dirname}));
  349. }
  350. // Dev only! Hot module reloading
  351. if (USE_HOT_MODULE_RELOAD && !NO_DEV_SERVER) {
  352. const backendAddress = `http://localhost:${SENTRY_BACKEND_PORT}/`;
  353. appConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
  354. appConfig.devServer = {
  355. headers: {
  356. 'Access-Control-Allow-Origin': '*',
  357. 'Access-Control-Allow-Credentials': 'true',
  358. },
  359. // Required for getsentry
  360. disableHostCheck: true,
  361. contentBase: './src/sentry/static/sentry',
  362. hot: true,
  363. // If below is false, will reload on errors
  364. hotOnly: true,
  365. port: SENTRY_WEBPACK_PROXY_PORT,
  366. stats: 'errors-only',
  367. overlay: true,
  368. watchOptions: {
  369. ignored: ['node_modules'],
  370. },
  371. publicPath: '/_webpack',
  372. proxy: {'!/_webpack': backendAddress},
  373. before: app =>
  374. app.use((req, _res, next) => {
  375. req.url = req.url.replace(/^\/_static\/[^\/]+\/sentry\/dist/, '/_webpack');
  376. next();
  377. }),
  378. };
  379. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  380. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  381. // backend, otherwise ALL requests are rewritten to a development index.html.
  382. // Thus completely separating the frontend from serving any pages through the
  383. // backend.
  384. //
  385. // THIS IS EXPERIMENTAL. Various sentry pages still rely on django to serve
  386. // html views.
  387. appConfig.devServer = !SENTRY_EXPERIMENTAL_SPA
  388. ? appConfig.devServer
  389. : {
  390. ...appConfig.devServer,
  391. before: () => undefined,
  392. publicPath: '/_assets',
  393. proxy: {'/api/': backendAddress},
  394. historyApiFallback: {
  395. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  396. },
  397. };
  398. }
  399. const minificationPlugins = [
  400. // This compression-webpack-plugin generates pre-compressed files
  401. // ending in .gz, to be picked up and served by our internal static media
  402. // server as well as nginx when paired with the gzip_static module.
  403. new CompressionPlugin({
  404. algorithm: 'gzip',
  405. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  406. }),
  407. new OptimizeCssAssetsPlugin(),
  408. // NOTE: In production mode webpack will automatically minify javascript
  409. // using the TerserWebpackPlugin.
  410. ];
  411. if (IS_PRODUCTION) {
  412. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  413. minificationPlugins.forEach(function(plugin) {
  414. appConfig.plugins.push(plugin);
  415. });
  416. }
  417. module.exports = appConfig;