No Description

webpack.config.prod.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. 'use strict';
  2. const autoprefixer = require('autoprefixer');
  3. const path = require('path');
  4. const webpack = require('webpack');
  5. const HtmlWebpackPlugin = require('html-webpack-plugin');
  6. const ExtractTextPlugin = require('extract-text-webpack-plugin');
  7. const ManifestPlugin = require('webpack-manifest-plugin');
  8. const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
  9. const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
  10. const eslintFormatter = require('react-dev-utils/eslintFormatter');
  11. const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
  12. const paths = require('./paths');
  13. const getClientEnvironment = require('./env');
  14. // Webpack uses `publicPath` to determine where the app is being served from.
  15. // It requires a trailing slash, or the file assets will get an incorrect path.
  16. const publicPath = paths.servedPath;
  17. // Some apps do not use client-side routing with pushState.
  18. // For these, "homepage" can be set to "." to enable relative asset paths.
  19. const shouldUseRelativeAssetPaths = publicPath === './';
  20. // Source maps are resource heavy and can cause out of memory issue for large source files.
  21. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
  22. // `publicUrl` is just like `publicPath`, but we will provide it to our app
  23. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  24. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  25. const publicUrl = publicPath.slice(0, -1);
  26. // Get environment variables to inject into our app.
  27. const env = getClientEnvironment(publicUrl);
  28. // Assert this just to be safe.
  29. // Development builds of React are slow and not intended for production.
  30. if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  31. throw new Error('Production builds must have NODE_ENV=production.');
  32. }
  33. // Note: defined here because it will be used more than once.
  34. const cssFilename = 'static/css/[name].[contenthash:8].css';
  35. // ExtractTextPlugin expects the build output to be flat.
  36. // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
  37. // However, our output is structured with css, js and media folders.
  38. // To have this structure working with relative paths, we have to use custom options.
  39. const extractTextPluginOptions = shouldUseRelativeAssetPaths
  40. ? // Making sure that the publicPath goes back to to build folder.
  41. { publicPath: Array(cssFilename.split('/').length).join('../') }
  42. : {};
  43. // This is the production configuration.
  44. // It compiles slowly and is focused on producing a fast and minimal bundle.
  45. // The development configuration is different and lives in a separate file.
  46. module.exports = {
  47. // Don't attempt to continue if there are any errors.
  48. bail: true,
  49. // We generate sourcemaps in production. This is slow but gives good results.
  50. // You can exclude the *.map files from the build during deployment.
  51. devtool: shouldUseSourceMap ? 'source-map' : false,
  52. // In production, we only want to load the polyfills and the app code.
  53. entry: [require.resolve('./polyfills'), paths.appIndexJs],
  54. output: {
  55. // The build folder.
  56. path: paths.appBuild,
  57. // Generated JS file names (with nested folders).
  58. // There will be one main bundle, and one file per asynchronous chunk.
  59. // We don't currently advertise code splitting but Webpack supports it.
  60. filename: 'static/js/[name].[chunkhash:8].js',
  61. chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
  62. // We inferred the "public path" (such as / or /my-project) from homepage.
  63. publicPath: publicPath,
  64. // Point sourcemap entries to original disk location (format as URL on Windows)
  65. devtoolModuleFilenameTemplate: info =>
  66. path
  67. .relative(paths.appSrc, info.absoluteResourcePath)
  68. .replace(/\\/g, '/'),
  69. },
  70. resolve: {
  71. // This allows you to set a fallback for where Webpack should look for modules.
  72. // We placed these paths second because we want `node_modules` to "win"
  73. // if there are any conflicts. This matches Node resolution mechanism.
  74. // https://github.com/facebookincubator/create-react-app/issues/253
  75. modules: ['node_modules', paths.appNodeModules].concat(
  76. // It is guaranteed to exist because we tweak it in `env.js`
  77. process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
  78. ),
  79. // These are the reasonable defaults supported by the Node ecosystem.
  80. // We also include JSX as a common component filename extension to support
  81. // some tools, although we do not recommend using it, see:
  82. // https://github.com/facebookincubator/create-react-app/issues/290
  83. // `web` extension prefixes have been added for better support
  84. // for React Native Web.
  85. extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
  86. alias: {
  87. // Support React Native Web
  88. // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  89. 'react-native': 'react-native-web',
  90. },
  91. plugins: [
  92. // Prevents users from importing files from outside of src/ (or node_modules/).
  93. // This often causes confusion because we only process files within src/ with babel.
  94. // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  95. // please link the files into your node_modules/ and let module-resolution kick in.
  96. // Make sure your source files are compiled, as they will not be processed in any way.
  97. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  98. ],
  99. },
  100. module: {
  101. strictExportPresence: true,
  102. rules: [
  103. // TODO: Disable require.ensure as it's not a standard language feature.
  104. // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
  105. // { parser: { requireEnsure: false } },
  106. // First, run the linter.
  107. // It's important to do this before Babel processes the JS.
  108. {
  109. test: /\.(js|jsx|mjs)$/,
  110. enforce: 'pre',
  111. use: [
  112. {
  113. options: {
  114. formatter: eslintFormatter,
  115. eslintPath: require.resolve('eslint'),
  116. },
  117. loader: require.resolve('eslint-loader'),
  118. },
  119. ],
  120. include: paths.appSrc,
  121. },
  122. {
  123. // "oneOf" will traverse all following loaders until one will
  124. // match the requirements. When no loader matches it will fall
  125. // back to the "file" loader at the end of the loader list.
  126. oneOf: [
  127. // "url" loader works just like "file" loader but it also embeds
  128. // assets smaller than specified size as data URLs to avoid requests.
  129. {
  130. test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  131. loader: require.resolve('url-loader'),
  132. options: {
  133. limit: 10000,
  134. name: 'static/media/[name].[hash:8].[ext]',
  135. },
  136. },
  137. // Process JS with Babel.
  138. {
  139. test: /\.(js|jsx|mjs)$/,
  140. include: paths.appSrc,
  141. loader: require.resolve('babel-loader'),
  142. options: {
  143. compact: true,
  144. },
  145. },
  146. // The notation here is somewhat confusing.
  147. // "postcss" loader applies autoprefixer to our CSS.
  148. // "css" loader resolves paths in CSS and adds assets as dependencies.
  149. // "style" loader normally turns CSS into JS modules injecting <style>,
  150. // but unlike in development configuration, we do something different.
  151. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
  152. // (second argument), then grabs the result CSS and puts it into a
  153. // separate file in our build process. This way we actually ship
  154. // a single CSS file in production instead of JS code injecting <style>
  155. // tags. If you use code splitting, however, any async bundles will still
  156. // use the "style" loader inside the async code so CSS from them won't be
  157. // in the main CSS file.
  158. {
  159. test: /\.css$/,
  160. loader: ExtractTextPlugin.extract(
  161. Object.assign(
  162. {
  163. fallback: {
  164. loader: require.resolve('style-loader'),
  165. options: {
  166. hmr: false,
  167. },
  168. },
  169. use: [
  170. {
  171. loader: require.resolve('css-loader'),
  172. options: {
  173. importLoaders: 1,
  174. minimize: true,
  175. sourceMap: shouldUseSourceMap,
  176. },
  177. },
  178. {
  179. loader: require.resolve('postcss-loader'),
  180. options: {
  181. // Necessary for external CSS imports to work
  182. // https://github.com/facebookincubator/create-react-app/issues/2677
  183. ident: 'postcss',
  184. plugins: () => [
  185. require('postcss-flexbugs-fixes'),
  186. autoprefixer({
  187. browsers: [
  188. '>1%',
  189. 'last 4 versions',
  190. 'Firefox ESR',
  191. 'not ie < 9', // React doesn't support IE8 anyway
  192. ],
  193. flexbox: 'no-2009',
  194. }),
  195. ],
  196. },
  197. },
  198. ],
  199. },
  200. extractTextPluginOptions
  201. )
  202. ),
  203. // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
  204. },
  205. // "file" loader makes sure assets end up in the `build` folder.
  206. // When you `import` an asset, you get its filename.
  207. // This loader doesn't use a "test" so it will catch all modules
  208. // that fall through the other loaders.
  209. {
  210. loader: require.resolve('file-loader'),
  211. // Exclude `js` files to keep "css" loader working as it injects
  212. // it's runtime that would otherwise processed through "file" loader.
  213. // Also exclude `html` and `json` extensions so they get processed
  214. // by webpacks internal loaders.
  215. exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
  216. options: {
  217. name: 'static/media/[name].[hash:8].[ext]',
  218. },
  219. },
  220. // ** STOP ** Are you adding a new loader?
  221. // Make sure to add the new loader(s) before the "file" loader.
  222. ],
  223. },
  224. ],
  225. },
  226. plugins: [
  227. // Makes some environment variables available in index.html.
  228. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  229. // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  230. // In production, it will be an empty string unless you specify "homepage"
  231. // in `package.json`, in which case it will be the pathname of that URL.
  232. new InterpolateHtmlPlugin(env.raw),
  233. // Generates an `index.html` file with the <script> injected.
  234. new HtmlWebpackPlugin({
  235. inject: true,
  236. template: paths.appHtml,
  237. minify: {
  238. removeComments: true,
  239. collapseWhitespace: true,
  240. removeRedundantAttributes: true,
  241. useShortDoctype: true,
  242. removeEmptyAttributes: true,
  243. removeStyleLinkTypeAttributes: true,
  244. keepClosingSlash: true,
  245. minifyJS: true,
  246. minifyCSS: true,
  247. minifyURLs: true,
  248. },
  249. }),
  250. // Makes some environment variables available to the JS code, for example:
  251. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  252. // It is absolutely essential that NODE_ENV was set to production here.
  253. // Otherwise React will be compiled in the very slow development mode.
  254. new webpack.DefinePlugin(env.stringified),
  255. // Minify the code.
  256. new webpack.optimize.UglifyJsPlugin({
  257. compress: {
  258. warnings: false,
  259. // Disabled because of an issue with Uglify breaking seemingly valid code:
  260. // https://github.com/facebookincubator/create-react-app/issues/2376
  261. // Pending further investigation:
  262. // https://github.com/mishoo/UglifyJS2/issues/2011
  263. comparisons: false,
  264. },
  265. mangle: {
  266. safari10: true,
  267. },
  268. output: {
  269. comments: false,
  270. // Turned on because emoji and regex is not minified properly using default
  271. // https://github.com/facebookincubator/create-react-app/issues/2488
  272. ascii_only: true,
  273. },
  274. sourceMap: shouldUseSourceMap,
  275. }),
  276. // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
  277. new ExtractTextPlugin({
  278. filename: cssFilename,
  279. }),
  280. // Generate a manifest file which contains a mapping of all asset filenames
  281. // to their corresponding output file so that tools can pick it up without
  282. // having to parse `index.html`.
  283. new ManifestPlugin({
  284. fileName: 'asset-manifest.json',
  285. }),
  286. // Generate a service worker script that will precache, and keep up to date,
  287. // the HTML & assets that are part of the Webpack build.
  288. new SWPrecacheWebpackPlugin({
  289. // By default, a cache-busting query parameter is appended to requests
  290. // used to populate the caches, to ensure the responses are fresh.
  291. // If a URL is already hashed by Webpack, then there is no concern
  292. // about it being stale, and the cache-busting can be skipped.
  293. dontCacheBustUrlsMatching: /\.\w{8}\./,
  294. filename: 'service-worker.js',
  295. logger(message) {
  296. if (message.indexOf('Total precache size is') === 0) {
  297. // This message occurs for every build and is a bit too noisy.
  298. return;
  299. }
  300. if (message.indexOf('Skipping static resource') === 0) {
  301. // This message obscures real errors so we ignore it.
  302. // https://github.com/facebookincubator/create-react-app/issues/2612
  303. return;
  304. }
  305. console.log(message);
  306. },
  307. minify: true,
  308. // For unknown URLs, fallback to the index page
  309. navigateFallback: publicUrl + '/index.html',
  310. // Ignores URLs starting from /__ (useful for Firebase):
  311. // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
  312. navigateFallbackWhitelist: [/^(?!\/__).*/],
  313. // Don't precache sourcemaps (they're large) and build asset manifest:
  314. staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
  315. }),
  316. // Moment.js is an extremely popular library that bundles large locale files
  317. // by default due to how Webpack interprets its code. This is a practical
  318. // solution that requires the user to opt into importing specific locales.
  319. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  320. // You can remove this if you don't use Moment.js:
  321. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  322. ],
  323. // Some libraries import Node modules but don't use them in the browser.
  324. // Tell Webpack to provide empty mocks for them so importing them works.
  325. node: {
  326. dgram: 'empty',
  327. fs: 'empty',
  328. net: 'empty',
  329. tls: 'empty',
  330. child_process: 'empty',
  331. },
  332. };