webpack.config.prod.js 12 KB

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