webpack.config.prod.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
  11. const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
  12. const paths = require('./paths');
  13. const getClientEnvironment = require('./env');
  14. const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
  15. const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
  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 !== 'false';
  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. // "url" loader works just like "file" loader but it also embeds
  132. // assets smaller than specified size as data URLs to avoid requests.
  133. {
  134. test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  135. loader: require.resolve('url-loader'),
  136. options: {
  137. limit: 10000,
  138. name: 'static/media/[name].[hash:8].[ext]',
  139. },
  140. },
  141. {
  142. test: /\.(js|jsx|mjs)$/,
  143. include: paths.appSrc,
  144. loader: require.resolve('babel-loader'),
  145. options: {
  146. compact: true,
  147. },
  148. },
  149. // Compile .tsx?
  150. {
  151. test: /\.(ts|tsx)$/,
  152. include: paths.appSrc,
  153. use: [
  154. {
  155. loader: require.resolve('ts-loader'),
  156. options: {
  157. // disable type checker - we will use it in fork plugin
  158. transpileOnly: true,
  159. configFile: paths.appTsProdConfig,
  160. },
  161. },
  162. ],
  163. },
  164. // The notation here is somewhat confusing.
  165. // "postcss" loader applies autoprefixer to our CSS.
  166. // "css" loader resolves paths in CSS and adds assets as dependencies.
  167. // "style" loader normally turns CSS into JS modules injecting <style>,
  168. // but unlike in development configuration, we do something different.
  169. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
  170. // (second argument), then grabs the result CSS and puts it into a
  171. // separate file in our build process. This way we actually ship
  172. // a single CSS file in production instead of JS code injecting <style>
  173. // tags. If you use code splitting, however, any async bundles will still
  174. // use the "style" loader inside the async code so CSS from them won't be
  175. // in the main CSS file.
  176. {
  177. test: /\.css$/,
  178. loader: ExtractTextPlugin.extract(
  179. Object.assign(
  180. {
  181. fallback: {
  182. loader: require.resolve('style-loader'),
  183. options: {
  184. hmr: false,
  185. },
  186. },
  187. use: [
  188. {
  189. loader: require.resolve('css-loader'),
  190. options: {
  191. importLoaders: 1,
  192. minimize: true,
  193. sourceMap: shouldUseSourceMap,
  194. },
  195. },
  196. {
  197. loader: require.resolve('postcss-loader'),
  198. options: {
  199. // Necessary for external CSS imports to work
  200. // https://github.com/facebookincubator/create-react-app/issues/2677
  201. ident: 'postcss',
  202. plugins: () => [
  203. require('postcss-flexbugs-fixes'),
  204. autoprefixer({
  205. browsers: [
  206. '>1%',
  207. 'last 4 versions',
  208. 'Firefox ESR',
  209. 'not ie < 9', // React doesn't support IE8 anyway
  210. ],
  211. flexbox: 'no-2009',
  212. }),
  213. ],
  214. },
  215. },
  216. ],
  217. },
  218. extractTextPluginOptions
  219. )
  220. ),
  221. // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
  222. },
  223. // "file" loader makes sure assets end up in the `build` folder.
  224. // When you `import` an asset, you get its filename.
  225. // This loader doesn't use a "test" so it will catch all modules
  226. // that fall through the other loaders.
  227. {
  228. loader: require.resolve('file-loader'),
  229. // Exclude `js` files to keep "css" loader working as it injects
  230. // it's runtime that would otherwise processed through "file" loader.
  231. // Also exclude `html` and `json` extensions so they get processed
  232. // by webpacks internal loaders.
  233. exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
  234. options: {
  235. name: 'static/media/[name].[hash:8].[ext]',
  236. },
  237. },
  238. // ** STOP ** Are you adding a new loader?
  239. // Make sure to add the new loader(s) before the "file" loader.
  240. ],
  241. },
  242. ],
  243. },
  244. plugins: [
  245. // Makes some environment variables available in index.html.
  246. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  247. // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  248. // In production, it will be an empty string unless you specify "homepage"
  249. // in `package.json`, in which case it will be the pathname of that URL.
  250. new InterpolateHtmlPlugin(env.raw),
  251. // Generates an `index.html` file with the <script> injected.
  252. new HtmlWebpackPlugin({
  253. inject: true,
  254. template: paths.appHtml,
  255. minify: {
  256. removeComments: true,
  257. collapseWhitespace: true,
  258. removeRedundantAttributes: true,
  259. useShortDoctype: true,
  260. removeEmptyAttributes: true,
  261. removeStyleLinkTypeAttributes: true,
  262. keepClosingSlash: true,
  263. minifyJS: true,
  264. minifyCSS: true,
  265. minifyURLs: true,
  266. },
  267. }),
  268. // Makes some environment variables available to the JS code, for example:
  269. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  270. // It is absolutely essential that NODE_ENV was set to production here.
  271. // Otherwise React will be compiled in the very slow development mode.
  272. new webpack.DefinePlugin(env.stringified),
  273. // Minify the code.
  274. new UglifyJsPlugin({
  275. uglifyOptions: {
  276. parse: {
  277. // we want uglify-js to parse ecma 8 code. However we want it to output
  278. // ecma 5 compliant code, to avoid issues with older browsers, this is
  279. // whey we put `ecma: 5` to the compress and output section
  280. // https://github.com/facebook/create-react-app/pull/4234
  281. ecma: 8,
  282. },
  283. compress: {
  284. ecma: 5,
  285. warnings: false,
  286. // Disabled because of an issue with Uglify breaking seemingly valid code:
  287. // https://github.com/facebook/create-react-app/issues/2376
  288. // Pending further investigation:
  289. // https://github.com/mishoo/UglifyJS2/issues/2011
  290. comparisons: false,
  291. // Don't inline functions with arguments, to avoid name collisions:
  292. // https://github.com/mishoo/UglifyJS2/issues/2842
  293. inline: 1,
  294. },
  295. mangle: {
  296. safari10: true,
  297. },
  298. output: {
  299. ecma: 5,
  300. comments: false,
  301. // Turned on because emoji and regex is not minified properly using default
  302. // https://github.com/facebook/create-react-app/issues/2488
  303. ascii_only: true,
  304. },
  305. },
  306. // Use multi-process parallel running to improve the build speed
  307. // Default number of concurrent runs: os.cpus().length - 1
  308. parallel: true,
  309. // Enable file caching
  310. cache: true,
  311. sourceMap: shouldUseSourceMap,
  312. }), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
  313. new ExtractTextPlugin({
  314. filename: cssFilename,
  315. }),
  316. // Generate a manifest file which contains a mapping of all asset filenames
  317. // to their corresponding output file so that tools can pick it up without
  318. // having to parse `index.html`.
  319. new ManifestPlugin({
  320. fileName: 'asset-manifest.json',
  321. }),
  322. // Generate a service worker script that will precache, and keep up to date,
  323. // the HTML & assets that are part of the Webpack build.
  324. new SWPrecacheWebpackPlugin({
  325. // By default, a cache-busting query parameter is appended to requests
  326. // used to populate the caches, to ensure the responses are fresh.
  327. // If a URL is already hashed by Webpack, then there is no concern
  328. // about it being stale, and the cache-busting can be skipped.
  329. dontCacheBustUrlsMatching: /\.\w{8}\./,
  330. filename: 'service-worker.js',
  331. logger(message) {
  332. if (message.indexOf('Total precache size is') === 0) {
  333. // This message occurs for every build and is a bit too noisy.
  334. return;
  335. }
  336. if (message.indexOf('Skipping static resource') === 0) {
  337. // This message obscures real errors so we ignore it.
  338. // https://github.com/facebookincubator/create-react-app/issues/2612
  339. return;
  340. }
  341. console.log(message);
  342. },
  343. minify: true,
  344. // For unknown URLs, fallback to the index page
  345. navigateFallback: publicUrl + '/index.html',
  346. // Ignores URLs starting from /__ (useful for Firebase):
  347. // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
  348. navigateFallbackWhitelist: [/^(?!\/__).*/],
  349. // Don't precache sourcemaps (they're large) and build asset manifest:
  350. staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
  351. }),
  352. // Moment.js is an extremely popular library that bundles large locale files
  353. // by default due to how Webpack interprets its code. This is a practical
  354. // solution that requires the user to opt into importing specific locales.
  355. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  356. // You can remove this if you don't use Moment.js:
  357. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  358. // Perform type checking and linting in a separate process to speed up compilation
  359. new ForkTsCheckerWebpackPlugin({
  360. async: false,
  361. tsconfig: paths.appTsProdConfig,
  362. tslint: paths.appTsLint,
  363. }),
  364. ],
  365. // Some libraries import Node modules but don't use them in the browser.
  366. // Tell Webpack to provide empty mocks for them so importing them works.
  367. node: {
  368. dgram: 'empty',
  369. fs: 'empty',
  370. net: 'empty',
  371. tls: 'empty',
  372. child_process: 'empty',
  373. },
  374. };