webpack.config.js 14 KB

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