webpack.config.js 11 KB

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