webpack.config.js 12 KB

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