webpack.config.js 11 KB

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