webpack.config.prod.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. 'use strict';
  2. const path = require('path');
  3. const webpack = require('webpack');
  4. const PnpWebpackPlugin = require('pnp-webpack-plugin');
  5. const HtmlWebpackPlugin = require('html-webpack-plugin');
  6. const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
  7. const TerserPlugin = require('terser-webpack-plugin');
  8. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  9. const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  10. const safePostCssParser = require('postcss-safe-parser');
  11. const ManifestPlugin = require('webpack-manifest-plugin');
  12. const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
  13. const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
  14. const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
  15. const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
  16. const paths = require('./paths');
  17. const getClientEnvironment = require('./env');
  18. const getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');
  19. const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
  20. // Webpack uses `publicPath` to determine where the app is being served from.
  21. // It requires a trailing slash, or the file assets will get an incorrect path.
  22. const publicPath = paths.servedPath;
  23. // Some apps do not use client-side routing with pushState.
  24. // For these, "homepage" can be set to "." to enable relative asset paths.
  25. const shouldUseRelativeAssetPaths = publicPath === './';
  26. // Source maps are resource heavy and can cause out of memory issue for large source files.
  27. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
  28. // `publicUrl` is just like `publicPath`, but we will provide it to our app
  29. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  30. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  31. const publicUrl = publicPath.slice(0, -1);
  32. // Get environment variables to inject into our app.
  33. const env = getClientEnvironment(publicUrl);
  34. // Assert this just to be safe.
  35. // Development builds of React are slow and not intended for production.
  36. if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  37. throw new Error('Production builds must have NODE_ENV=production.');
  38. }
  39. // style files regexes
  40. const cssRegex = /\.css$/;
  41. const cssModuleRegex = /\.module\.css$/;
  42. const sassRegex = /\.(scss|sass)$/;
  43. const sassModuleRegex = /\.module\.(scss|sass)$/;
  44. const lessRegex = /\.less$/;
  45. const lessModuleRegex = /\.module\.less/;
  46. // common function to get style loaders
  47. const getStyleLoaders = (cssOptions, preProcessor) => {
  48. const loaders = [
  49. {
  50. loader: MiniCssExtractPlugin.loader,
  51. options: Object.assign(
  52. {},
  53. shouldUseRelativeAssetPaths ? { publicPath: '../../' } : undefined
  54. ),
  55. },
  56. {
  57. loader: require.resolve('css-loader'),
  58. options: cssOptions,
  59. },
  60. {
  61. // Options for PostCSS as we reference these options twice
  62. // Adds vendor prefixing based on your specified browser support in
  63. // package.json
  64. loader: require.resolve('postcss-loader'),
  65. options: {
  66. // Necessary for external CSS imports to work
  67. // https://github.com/facebook/create-react-app/issues/2677
  68. ident: 'postcss',
  69. plugins: () => [
  70. require('postcss-flexbugs-fixes'),
  71. require('postcss-preset-env')({
  72. autoprefixer: {
  73. flexbox: 'no-2009',
  74. },
  75. stage: 3,
  76. }),
  77. ],
  78. sourceMap: shouldUseSourceMap,
  79. },
  80. },
  81. ];
  82. if (preProcessor) {
  83. loaders.push({
  84. loader: require.resolve(preProcessor),
  85. options: {
  86. sourceMap: shouldUseSourceMap,
  87. },
  88. });
  89. }
  90. return loaders;
  91. };
  92. // This is the production configuration.
  93. // It compiles slowly and is focused on producing a fast and minimal bundle.
  94. // The development configuration is different and lives in a separate file.
  95. module.exports = {
  96. mode: 'production',
  97. // Don't attempt to continue if there are any errors.
  98. bail: true,
  99. // We generate sourcemaps in production. This is slow but gives good results.
  100. // You can exclude the *.map files from the build during deployment.
  101. devtool: shouldUseSourceMap ? 'source-map' : false,
  102. // In production, we only want to load the app code.
  103. entry: [paths.appIndexJs],
  104. output: {
  105. // The build folder.
  106. path: paths.appBuild,
  107. // Generated JS file names (with nested folders).
  108. // There will be one main bundle, and one file per asynchronous chunk.
  109. // We don't currently advertise code splitting but Webpack supports it.
  110. filename: 'static/js/[name].[chunkhash:8].js',
  111. chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
  112. // We inferred the "public path" (such as / or /my-project) from homepage.
  113. publicPath: publicPath,
  114. // Point sourcemap entries to original disk location (format as URL on Windows)
  115. devtoolModuleFilenameTemplate: info =>
  116. path
  117. .relative(paths.appSrc, info.absoluteResourcePath)
  118. .replace(/\\/g, '/'),
  119. },
  120. optimization: {
  121. minimizer: [
  122. new TerserPlugin({
  123. terserOptions: {
  124. parse: {
  125. // we want terser to parse ecma 8 code. However, we don't want it
  126. // to apply any minfication steps that turns valid ecma 5 code
  127. // into invalid ecma 5 code. This is why the 'compress' and 'output'
  128. // sections only apply transformations that are ecma 5 safe
  129. // https://github.com/facebook/create-react-app/pull/4234
  130. ecma: 8,
  131. },
  132. compress: {
  133. ecma: 5,
  134. warnings: false,
  135. // Disabled because of an issue with Uglify breaking seemingly valid code:
  136. // https://github.com/facebook/create-react-app/issues/2376
  137. // Pending further investigation:
  138. // https://github.com/mishoo/UglifyJS2/issues/2011
  139. comparisons: false,
  140. // Disabled because of an issue with Terser breaking valid code:
  141. // https://github.com/facebook/create-react-app/issues/5250
  142. // Pending futher investigation:
  143. // https://github.com/terser-js/terser/issues/120
  144. inline: 2,
  145. },
  146. mangle: {
  147. safari10: true,
  148. },
  149. output: {
  150. ecma: 5,
  151. comments: false,
  152. // Turned on because emoji and regex is not minified properly using default
  153. // https://github.com/facebook/create-react-app/issues/2488
  154. ascii_only: true,
  155. },
  156. },
  157. // Use multi-process parallel running to improve the build speed
  158. // Default number of concurrent runs: os.cpus().length - 1
  159. parallel: true,
  160. // Enable file caching
  161. cache: true,
  162. sourceMap: shouldUseSourceMap,
  163. }),
  164. new OptimizeCSSAssetsPlugin({
  165. cssProcessorOptions: {
  166. parser: safePostCssParser,
  167. map: shouldUseSourceMap
  168. ? {
  169. // `inline: false` forces the sourcemap to be output into a
  170. // separate file
  171. inline: false,
  172. // `annotation: true` appends the sourceMappingURL to the end of
  173. // the css file, helping the browser find the sourcemap
  174. annotation: true,
  175. }
  176. : false,
  177. },
  178. }),
  179. ],
  180. // Automatically split vendor and commons
  181. // https://twitter.com/wSokra/status/969633336732905474
  182. // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
  183. splitChunks: {
  184. chunks: 'all',
  185. name: false,
  186. },
  187. // Keep the runtime chunk seperated to enable long term caching
  188. // https://twitter.com/wSokra/status/969679223278505985
  189. runtimeChunk: true,
  190. },
  191. resolve: {
  192. // This allows you to set a fallback for where Webpack should look for modules.
  193. // We placed these paths second because we want `node_modules` to "win"
  194. // if there are any conflicts. This matches Node resolution mechanism.
  195. // https://github.com/facebook/create-react-app/issues/253
  196. modules: ['node_modules'].concat(
  197. // It is guaranteed to exist because we tweak it in `env.js`
  198. process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
  199. ),
  200. // These are the reasonable defaults supported by the Node ecosystem.
  201. // We also include JSX as a common component filename extension to support
  202. // some tools, although we do not recommend using it, see:
  203. // https://github.com/facebook/create-react-app/issues/290
  204. // `web` extension prefixes have been added for better support
  205. // for React Native Web.
  206. extensions: ['.mjs', '.web.js', '.js', '.json', '.web.jsx', '.jsx'],
  207. alias: {
  208. // Support React Native Web
  209. // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  210. 'react-native': 'react-native-web',
  211. // 全局相对路径别名,处理相对路径过长和繁琐问题
  212. '@': paths.appSrc
  213. },
  214. plugins: [
  215. // Adds support for installing with Plug'n'Play, leading to faster installs and adding
  216. // guards against forgotten dependencies and such.
  217. PnpWebpackPlugin,
  218. // Prevents users from importing files from outside of src/ (or node_modules/).
  219. // This often causes confusion because we only process files within src/ with babel.
  220. // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  221. // please link the files into your node_modules/ and let module-resolution kick in.
  222. // Make sure your source files are compiled, as they will not be processed in any way.
  223. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  224. ],
  225. },
  226. resolveLoader: {
  227. plugins: [
  228. // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
  229. // from the current package.
  230. PnpWebpackPlugin.moduleLoader(module),
  231. ],
  232. },
  233. module: {
  234. strictExportPresence: true,
  235. rules: [
  236. // Disable require.ensure as it's not a standard language feature.
  237. { parser: { requireEnsure: false } },
  238. // First, run the linter.
  239. // It's important to do this before Babel processes the JS.
  240. {
  241. test: /\.(js|mjs|jsx)$/,
  242. enforce: 'pre',
  243. use: [
  244. {
  245. options: {
  246. formatter: require.resolve('react-dev-utils/eslintFormatter'),
  247. eslintPath: require.resolve('eslint'),
  248. },
  249. loader: require.resolve('eslint-loader'),
  250. },
  251. ],
  252. include: paths.appSrc,
  253. },
  254. {
  255. // "oneOf" will traverse all following loaders until one will
  256. // match the requirements. When no loader matches it will fall
  257. // back to the "file" loader at the end of the loader list.
  258. oneOf: [
  259. // "url" loader works just like "file" loader but it also embeds
  260. // assets smaller than specified size as data URLs to avoid requests.
  261. {
  262. test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  263. loader: require.resolve('url-loader'),
  264. options: {
  265. limit: 10000,
  266. name: 'static/media/[name].[hash:8].[ext]',
  267. },
  268. },
  269. // Process application JS with Babel.
  270. // The preset includes JSX, Flow, and some ESnext features.
  271. {
  272. test: /\.(js|mjs|jsx)$/,
  273. include: paths.appSrc,
  274. loader: require.resolve('babel-loader'),
  275. options: {
  276. customize: require.resolve(
  277. 'babel-preset-react-app/webpack-overrides'
  278. ),
  279. plugins: [
  280. [
  281. require.resolve('babel-plugin-named-asset-import'),
  282. {
  283. loaderMap: {
  284. svg: {
  285. ReactComponent: '@svgr/webpack?-prettier,-svgo![path]',
  286. },
  287. },
  288. },
  289. ],
  290. ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }],
  291. ],
  292. cacheDirectory: true,
  293. // Save disk space when time isn't as important
  294. cacheCompression: true,
  295. compact: true,
  296. },
  297. },
  298. // Process any JS outside of the app with Babel.
  299. // Unlike the application JS, we only compile the standard ES features.
  300. {
  301. test: /\.(js|mjs)$/,
  302. exclude: /@babel(?:\/|\\{1,2})runtime/,
  303. loader: require.resolve('babel-loader'),
  304. options: {
  305. babelrc: false,
  306. configFile: false,
  307. compact: false,
  308. presets: [
  309. [
  310. require.resolve('babel-preset-react-app/dependencies'),
  311. { helpers: true },
  312. ],
  313. ],
  314. cacheDirectory: true,
  315. // Save disk space when time isn't as important
  316. cacheCompression: true,
  317. // If an error happens in a package, it's possible to be
  318. // because it was compiled. Thus, we don't want the browser
  319. // debugger to show the original code. Instead, the code
  320. // being evaluated would be much more helpful.
  321. sourceMaps: false,
  322. },
  323. },
  324. // "postcss" loader applies autoprefixer to our CSS.
  325. // "css" loader resolves paths in CSS and adds assets as dependencies.
  326. // `MiniCSSExtractPlugin` extracts styles into CSS
  327. // files. If you use code splitting, async bundles will have their own separate CSS chunk file.
  328. // By default we support CSS Modules with the extension .module.css
  329. {
  330. test: cssRegex,
  331. exclude: cssModuleRegex,
  332. loader: getStyleLoaders({
  333. importLoaders: 1,
  334. sourceMap: shouldUseSourceMap,
  335. }),
  336. // Don't consider CSS imports dead code even if the
  337. // containing package claims to have no side effects.
  338. // Remove this when webpack adds a warning or an error for this.
  339. // See https://github.com/webpack/webpack/issues/6571
  340. sideEffects: true,
  341. },
  342. // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
  343. // using the extension .module.css
  344. {
  345. test: cssModuleRegex,
  346. loader: getStyleLoaders({
  347. importLoaders: 1,
  348. sourceMap: shouldUseSourceMap,
  349. modules: true,
  350. getLocalIdent: getCSSModuleLocalIdent,
  351. }),
  352. },
  353. // Opt-in support for SASS. The logic here is somewhat similar
  354. // as in the CSS routine, except that "sass-loader" runs first
  355. // to compile SASS files into CSS.
  356. // By default we support SASS Modules with the
  357. // extensions .module.scss or .module.sass
  358. {
  359. test: sassRegex,
  360. exclude: sassModuleRegex,
  361. loader: getStyleLoaders(
  362. {
  363. importLoaders: 2,
  364. sourceMap: shouldUseSourceMap,
  365. },
  366. 'sass-loader'
  367. ),
  368. // Don't consider CSS imports dead code even if the
  369. // containing package claims to have no side effects.
  370. // Remove this when webpack adds a warning or an error for this.
  371. // See https://github.com/webpack/webpack/issues/6571
  372. sideEffects: true,
  373. },
  374. // Adds support for CSS Modules, but using SASS
  375. // using the extension .module.scss or .module.sass
  376. {
  377. test: sassModuleRegex,
  378. loader: getStyleLoaders(
  379. {
  380. importLoaders: 2,
  381. sourceMap: shouldUseSourceMap,
  382. modules: true,
  383. getLocalIdent: getCSSModuleLocalIdent,
  384. },
  385. 'sass-loader'
  386. ),
  387. },
  388. // Opt-in support for LESS (using .less extensions).
  389. {
  390. test: lessRegex,
  391. exclude: lessModuleRegex,
  392. loader: getStyleLoaders({
  393. importLoaders: 2,
  394. sourceMap: shouldUseSourceMap,
  395. }, 'less-loader'),
  396. },
  397. // Adds support for CSS Modules, but using LESS
  398. // using the extension .module.scss or .module.sass
  399. {
  400. test: lessModuleRegex,
  401. loader: getStyleLoaders(
  402. {
  403. importLoaders: 2,
  404. sourceMap: shouldUseSourceMap,
  405. modules: true,
  406. getLocalIdent: getCSSModuleLocalIdent,
  407. },
  408. 'less-loader'
  409. ),
  410. },
  411. // "file" loader makes sure assets end up in the `build` folder.
  412. // When you `import` an asset, you get its filename.
  413. // This loader doesn't use a "test" so it will catch all modules
  414. // that fall through the other loaders.
  415. {
  416. loader: require.resolve('file-loader'),
  417. // Exclude `js` files to keep "css" loader working as it injects
  418. // it's runtime that would otherwise be processed through "file" loader.
  419. // Also exclude `html` and `json` extensions so they get processed
  420. // by webpacks internal loaders.
  421. exclude: [/\.(js|mjs|jsx)$/, /\.html$/, /\.json$/],
  422. options: {
  423. name: 'static/media/[name].[hash:8].[ext]',
  424. },
  425. },
  426. // ** STOP ** Are you adding a new loader?
  427. // Make sure to add the new loader(s) before the "file" loader.
  428. ],
  429. },
  430. ],
  431. },
  432. plugins: [
  433. // Generates an `index.html` file with the <script> injected.
  434. new HtmlWebpackPlugin({
  435. inject: true,
  436. template: paths.appHtml,
  437. minify: {
  438. removeComments: true,
  439. collapseWhitespace: true,
  440. removeRedundantAttributes: true,
  441. useShortDoctype: true,
  442. removeEmptyAttributes: true,
  443. removeStyleLinkTypeAttributes: true,
  444. keepClosingSlash: true,
  445. minifyJS: true,
  446. minifyCSS: true,
  447. minifyURLs: true,
  448. },
  449. }),
  450. // Inlines the webpack runtime script. This script is too small to warrant
  451. // a network request.
  452. new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime~.+[.]js/]),
  453. // Makes some environment variables available in index.html.
  454. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  455. // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  456. // In production, it will be an empty string unless you specify "homepage"
  457. // in `package.json`, in which case it will be the pathname of that URL.
  458. new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  459. // This gives some necessary context to module not found errors, such as
  460. // the requesting resource.
  461. new ModuleNotFoundPlugin(paths.appPath),
  462. // Makes some environment variables available to the JS code, for example:
  463. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  464. // It is absolutely essential that NODE_ENV was set to production here.
  465. // Otherwise React will be compiled in the very slow development mode.
  466. new webpack.DefinePlugin(env.stringified),
  467. new MiniCssExtractPlugin({
  468. // Options similar to the same options in webpackOptions.output
  469. // both options are optional
  470. filename: 'static/css/[name].[contenthash:8].css',
  471. chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
  472. }),
  473. // Generate a manifest file which contains a mapping of all asset filenames
  474. // to their corresponding output file so that tools can pick it up without
  475. // having to parse `index.html`.
  476. new ManifestPlugin({
  477. fileName: 'asset-manifest.json',
  478. publicPath: publicPath,
  479. }),
  480. // Moment.js is an extremely popular library that bundles large locale files
  481. // by default due to how Webpack interprets its code. This is a practical
  482. // solution that requires the user to opt into importing specific locales.
  483. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  484. // You can remove this if you don't use Moment.js:
  485. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  486. // Generate a service worker script that will precache, and keep up to date,
  487. // the HTML & assets that are part of the Webpack build.
  488. new WorkboxWebpackPlugin.GenerateSW({
  489. clientsClaim: true,
  490. exclude: [/\.map$/, /asset-manifest\.json$/],
  491. importWorkboxFrom: 'cdn',
  492. navigateFallback: publicUrl + '/index.html',
  493. navigateFallbackBlacklist: [
  494. // Exclude URLs starting with /_, as they're likely an API call
  495. new RegExp('^/_'),
  496. // Exclude URLs containing a dot, as they're likely a resource in
  497. // public/ and not a SPA route
  498. new RegExp('/[^/]+\\.[^/]+$'),
  499. ],
  500. }),
  501. ],
  502. // Some libraries import Node modules but don't use them in the browser.
  503. // Tell Webpack to provide empty mocks for them so importing them works.
  504. node: {
  505. dgram: 'empty',
  506. fs: 'empty',
  507. net: 'empty',
  508. tls: 'empty',
  509. child_process: 'empty',
  510. },
  511. // Turn off performance processing because we utilize
  512. // our own hints via the FileSizeReporter
  513. performance: false,
  514. };