Guest User

Untitled

a guest
Jul 30th, 2019
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const fs = require('fs');
  4. const isWsl = require('is-wsl');
  5. const path = require('path');
  6. const webpack = require('webpack');
  7. const resolve = require('resolve');
  8. const PnpWebpackPlugin = require('pnp-webpack-plugin');
  9. const HtmlWebpackPlugin = require('html-webpack-plugin');
  10. const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
  11. const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
  12. const TerserPlugin = require('terser-webpack-plugin');
  13. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  14. const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  15. const safePostCssParser = require('postcss-safe-parser');
  16. const ManifestPlugin = require('webpack-manifest-plugin');
  17. const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
  18. const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
  19. const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
  20. const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
  21. const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
  22. const paths = require('./paths');
  23. const modules = require('./modules');
  24. const getClientEnvironment = require('./env');
  25. const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
  26. const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
  27. const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
  28.  
  29. const postcssNormalize = require('postcss-normalize');
  30.  
  31. // Source maps are resource heavy and can cause out of memory issue for large source files.
  32. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
  33. // Some apps do not need the benefits of saving a web request, so not inlining the chunk
  34. // makes for a smoother build process.
  35. const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
  36.  
  37. // Check if TypeScript is setup
  38. const useTypeScript = fs.existsSync(paths.appTsConfig);
  39.  
  40. // style files regexes
  41. const cssRegex = /\.css$/;
  42. const cssModuleRegex = /\.module\.css$/;
  43. const sassRegex = /\.(scss|sass)$/;
  44. const sassModuleRegex = /\.module\.(scss|sass)$/;
  45.  
  46. // This is the production and development configuration.
  47. // It is focused on developer experience, fast rebuilds, and a minimal bundle.
  48. module.exports = function (webpackEnv) {
  49.     const isEnvDevelopment = webpackEnv === 'development';
  50.     const isEnvProduction = webpackEnv === 'production';
  51.  
  52.     // Webpack uses `publicPath` to determine where the app is being served from.
  53.     // It requires a trailing slash, or the file assets will get an incorrect path.
  54.     // In development, we always serve from the root. This makes config easier.
  55.     const publicPath = isEnvProduction
  56.         ? paths.servedPath
  57.         : isEnvDevelopment && '/';
  58.     // Some apps do not use client-side routing with pushState.
  59.     // For these, "homepage" can be set to "." to enable relative asset paths.
  60.     const shouldUseRelativeAssetPaths = publicPath === './';
  61.  
  62.     // `publicUrl` is just like `publicPath`, but we will provide it to our app
  63.     // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  64.     // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  65.     const publicUrl = isEnvProduction
  66.         ? publicPath.slice(0, -1)
  67.         : isEnvDevelopment && '';
  68.     // Get environment variables to inject into our app.
  69.     const env = getClientEnvironment(publicUrl);
  70.  
  71.     // common function to get style loaders
  72.     const getStyleLoaders = (cssOptions, preProcessor) => {
  73.         const loaders = [
  74.             isEnvDevelopment && require.resolve('style-loader'),
  75.             isEnvProduction && {
  76.                 loader: MiniCssExtractPlugin.loader,
  77.                 options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
  78.             },
  79.             {
  80.                 loader: require.resolve('css-loader'),
  81.                 options: cssOptions,
  82.             },
  83.             {
  84.                 // Options for PostCSS as we reference these options twice
  85.                 // Adds vendor prefixing based on your specified browser support in
  86.                 // package.json
  87.                 loader: require.resolve('postcss-loader'),
  88.                 options: {
  89.                     // Necessary for external CSS imports to work
  90.                     // https://github.com/facebook/create-react-app/issues/2677
  91.                     ident: 'postcss',
  92.                     plugins: () => [
  93.                         require('postcss-flexbugs-fixes'),
  94.                         require('postcss-preset-env')({
  95.                             autoprefixer: {
  96.                                 flexbox: 'no-2009',
  97.                             },
  98.                             stage: 3,
  99.                         }),
  100.                         // Adds PostCSS Normalize as the reset css with default options,
  101.                         // so that it honors browserslist config in package.json
  102.                         // which in turn let's users customize the target behavior as per their needs.
  103.                         postcssNormalize(),
  104.                     ],
  105.                     sourceMap: isEnvProduction && shouldUseSourceMap,
  106.                 },
  107.             },
  108.         ].filter(Boolean);
  109.         if (preProcessor) {
  110.             loaders.push({
  111.                 loader: require.resolve(preProcessor),
  112.                 options: {
  113.                     sourceMap: isEnvProduction && shouldUseSourceMap,
  114.                 },
  115.             });
  116.         }
  117.         return loaders;
  118.     };
  119.  
  120.     return {
  121.         mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
  122.         // Stop compilation early in production
  123.         bail: isEnvProduction,
  124.         devtool: isEnvProduction
  125.             ? shouldUseSourceMap
  126.                 ? 'source-map'
  127.                 : false
  128.             : isEnvDevelopment && 'cheap-module-source-map',
  129.         // These are the "entry points" to our application.
  130.         // This means they will be the "root" imports that are included in JS bundle.
  131.         entry: [
  132.             // Include an alternative client for WebpackDevServer. A client's job is to
  133.             // connect to WebpackDevServer by a socket and get notified about changes.
  134.             // When you save a file, the client will either apply hot updates (in case
  135.             // of CSS changes), or refresh the page (in case of JS changes). When you
  136.             // make a syntax error, this client will display a syntax error overlay.
  137.             // Note: instead of the default WebpackDevServer client, we use a custom one
  138.             // to bring better experience for Create React App users. You can replace
  139.             // the line below with these two lines if you prefer the stock client:
  140.             // require.resolve('webpack-dev-server/client') + '?/',
  141.             // require.resolve('webpack/hot/dev-server'),
  142.             isEnvDevelopment &&
  143.             require.resolve('react-dev-utils/webpackHotDevClient'),
  144.             // Finally, this is your app's code:
  145.             paths.appIndexJs,
  146.             // We include the app code last so that if there is a runtime error during
  147.             // initialization, it doesn't blow up the WebpackDevServer client, and
  148.             // changing JS code would still trigger a refresh.
  149.         ].filter(Boolean),
  150.         output: {
  151.             // The build folder.
  152.             path: isEnvProduction ? paths.appBuild : undefined,
  153.             // Add /* filename */ comments to generated require()s in the output.
  154.             pathinfo: isEnvDevelopment,
  155.             // There will be one main bundle, and one file per asynchronous chunk.
  156.             // In development, it does not produce real files.
  157.             filename: isEnvProduction
  158.                 ? 'static/js/[name].[contenthash:8].js'
  159.                 : isEnvDevelopment && 'static/js/bundle.js',
  160.             // TODO: remove this when upgrading to webpack 5
  161.             futureEmitAssets: true,
  162.             // There are also additional JS chunk files if you use code splitting.
  163.             chunkFilename: isEnvProduction
  164.                 ? 'static/js/[name].[contenthash:8].chunk.js'
  165.                 : isEnvDevelopment && 'static/js/[name].chunk.js',
  166.             // We inferred the "public path" (such as / or /my-project) from homepage.
  167.             // We use "/" in development.
  168.             publicPath: publicPath,
  169.             // Point sourcemap entries to original disk location (format as URL on Windows)
  170.             devtoolModuleFilenameTemplate: isEnvProduction
  171.                 ? info =>
  172.                     path
  173.                         .relative(paths.appSrc, info.absoluteResourcePath)
  174.                         .replace(/\\/g, '/')
  175.                 : isEnvDevelopment &&
  176.                 (info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
  177.         },
  178.         optimization: {
  179.             minimize: isEnvProduction,
  180.             minimizer: [
  181.                 // This is only used in production mode
  182.                 new TerserPlugin({
  183.                     terserOptions: {
  184.                         parse: {
  185.                             // we want terser to parse ecma 8 code. However, we don't want it
  186.                             // to apply any minfication steps that turns valid ecma 5 code
  187.                             // into invalid ecma 5 code. This is why the 'compress' and 'output'
  188.                             // sections only apply transformations that are ecma 5 safe
  189.                             // https://github.com/facebook/create-react-app/pull/4234
  190.                             ecma: 8,
  191.                         },
  192.                         compress: {
  193.                             ecma: 5,
  194.                             warnings: false,
  195.                             // Disabled because of an issue with Uglify breaking seemingly valid code:
  196.                             // https://github.com/facebook/create-react-app/issues/2376
  197.                             // Pending further investigation:
  198.                             // https://github.com/mishoo/UglifyJS2/issues/2011
  199.                             comparisons: false,
  200.                             // Disabled because of an issue with Terser breaking valid code:
  201.                             // https://github.com/facebook/create-react-app/issues/5250
  202.                             // Pending futher investigation:
  203.                             // https://github.com/terser-js/terser/issues/120
  204.                             inline: 2,
  205.                         },
  206.                         mangle: {
  207.                             safari10: true,
  208.                         },
  209.                         output: {
  210.                             ecma: 5,
  211.                             comments: false,
  212.                             // Turned on because emoji and regex is not minified properly using default
  213.                             // https://github.com/facebook/create-react-app/issues/2488
  214.                             ascii_only: true,
  215.                         },
  216.                     },
  217.                     // Use multi-process parallel running to improve the build speed
  218.                     // Default number of concurrent runs: os.cpus().length - 1
  219.                     // Disabled on WSL (Windows Subsystem for Linux) due to an issue with Terser
  220.                     // https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
  221.                     parallel: !isWsl,
  222.                     // Enable file caching
  223.                     cache: true,
  224.                     sourceMap: shouldUseSourceMap,
  225.                 }),
  226.                 // This is only used in production mode
  227.                 new OptimizeCSSAssetsPlugin({
  228.                     cssProcessorOptions: {
  229.                         parser: safePostCssParser,
  230.                         map: shouldUseSourceMap
  231.                             ? {
  232.                                 // `inline: false` forces the sourcemap to be output into a
  233.                                 // separate file
  234.                                 inline: false,
  235.                                 // `annotation: true` appends the sourceMappingURL to the end of
  236.                                 // the css file, helping the browser find the sourcemap
  237.                                 annotation: true,
  238.                             }
  239.                             : false,
  240.                     },
  241.                 }),
  242.             ],
  243.             // Automatically split vendor and commons
  244.             // https://twitter.com/wSokra/status/969633336732905474
  245.             // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
  246.             splitChunks: {
  247.                 chunks: 'all',
  248.                 name: false,
  249.             },
  250.             // Keep the runtime chunk separated to enable long term caching
  251.             // https://twitter.com/wSokra/status/969679223278505985
  252.             runtimeChunk: true,
  253.         },
  254.         resolve: {
  255.             // This allows you to set a fallback for where Webpack should look for modules.
  256.             // We placed these paths second because we want `node_modules` to "win"
  257.             // if there are any conflicts. This matches Node resolution mechanism.
  258.             // https://github.com/facebook/create-react-app/issues/253
  259.             modules: ['node_modules', paths.appNodeModules].concat(
  260.                 modules.additionalModulePaths || []
  261.             ),
  262.             // These are the reasonable defaults supported by the Node ecosystem.
  263.             // We also include JSX as a common component filename extension to support
  264.             // some tools, although we do not recommend using it, see:
  265.             // https://github.com/facebook/create-react-app/issues/290
  266.             // `web` extension prefixes have been added for better support
  267.             // for React Native Web.
  268.             extensions: paths.moduleFileExtensions
  269.                 .map(ext => `.${ ext }`)
  270.                 .filter(ext => useTypeScript || !ext.includes('ts')),
  271.             alias: {
  272.                 // Support React Native Web
  273.                 // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  274.                 'react-native': 'react-native-web',
  275.             },
  276.             plugins: [
  277.                 // Adds support for installing with Plug'n'Play, leading to faster installs and adding
  278.                 // guards against forgotten dependencies and such.
  279.                 PnpWebpackPlugin,
  280.                 // Prevents users from importing files from outside of src/ (or node_modules/).
  281.                 // This often causes confusion because we only process files within src/ with babel.
  282.                 // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  283.                 // please link the files into your node_modules/ and let module-resolution kick in.
  284.                 // Make sure your source files are compiled, as they will not be processed in any way.
  285.                 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  286.             ],
  287.         },
  288.         resolveLoader: {
  289.             plugins: [
  290.                 // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
  291.                 // from the current package.
  292.                 PnpWebpackPlugin.moduleLoader(module),
  293.             ],
  294.         },
  295.         module: {
  296.             strictExportPresence: true,
  297.             rules: [
  298.                 // Disable require.ensure as it's not a standard language feature.
  299.                 { parser: { requireEnsure: false } },
  300.  
  301.                 // First, run the linter.
  302.                 // It's important to do this before Babel processes the JS.
  303.                 {
  304.                     test: /\.(js|mjs|jsx|ts|tsx)$/,
  305.                     enforce: 'pre',
  306.                     use: [
  307.                         {
  308.                             options: {
  309.                                 formatter: require.resolve('react-dev-utils/eslintFormatter'),
  310.                                 eslintPath: require.resolve('eslint'),
  311.  
  312.                             },
  313.                             loader: require.resolve('eslint-loader'),
  314.                         },
  315.                     ],
  316.                     include: paths.appSrc,
  317.                     exclude: [path.resolve(__dirname, 'src/SourceResolver/')]
  318.                 },
  319.                 {
  320.                     // "oneOf" will traverse all following loaders until one will
  321.                     // match the requirements. When no loader matches it will fall
  322.                     // back to the "file" loader at the end of the loader list.
  323.                     oneOf: [
  324.                         // "url" loader works like "file" loader except that it embeds assets
  325.                         // smaller than specified limit in bytes as data URLs to avoid requests.
  326.                         // A missing `test` is equivalent to a match.
  327.                         {
  328.                             test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  329.                             loader: require.resolve('url-loader'),
  330.                             options: {
  331.                                 limit: 10000,
  332.                                 name: 'static/media/[name].[hash:8].[ext]',
  333.                             },
  334.                             exclude: [path.resolve(__dirname, 'src/SourceResolver/')]
  335.                         },
  336.                         // Process application JS with Babel.
  337.                         // The preset includes JSX, Flow, TypeScript, and some ESnext features.
  338.                         {
  339.                             test: /\.(js|mjs|jsx|ts|tsx)$/,
  340.                             include: paths.appSrc,
  341.                             loader: require.resolve('babel-loader'),
  342.                             exclude: [path.resolve(__dirname, 'src/SourceResolver/')],
  343.                             options: {
  344.                                 customize: require.resolve(
  345.                                     'babel-preset-react-app/webpack-overrides'
  346.                                 ),
  347.  
  348.                                 plugins: [
  349.                                     [
  350.                                         require.resolve('babel-plugin-named-asset-import'),
  351.                                         {
  352.                                             loaderMap: {
  353.                                                 svg: {
  354.                                                     ReactComponent: '@svgr/webpack?-svgo,+ref![path]',
  355.                                                 },
  356.                                             },
  357.                                         },
  358.                                     ],
  359.                                 ],
  360.                                 // This is a feature of `babel-loader` for webpack (not Babel itself).
  361.                                 // It enables caching results in ./node_modules/.cache/babel-loader/
  362.                                 // directory for faster rebuilds.
  363.                                 cacheDirectory: true,
  364.                                 cacheCompression: isEnvProduction,
  365.                                 compact: isEnvProduction,
  366.                             },
  367.                         },
  368.                         // Process any JS outside of the app with Babel.
  369.                         // Unlike the application JS, we only compile the standard ES features.
  370.                         {
  371.                             test: /\.(js|mjs)$/,
  372.                             loader: require.resolve('babel-loader'),
  373.                             exclude: [/@babel(?:\/|\\{1,2})runtime/, path.resolve(__dirname, 'src/SourceResolver/')],
  374.                             options: {
  375.                                 babelrc: false,
  376.                                 configFile: false,
  377.                                 compact: false,
  378.                                 presets: [
  379.                                     [
  380.                                         require.resolve('babel-preset-react-app/dependencies'),
  381.                                         { helpers: true },
  382.                                     ],
  383.                                 ],
  384.                                 cacheDirectory: true,
  385.                                 cacheCompression: isEnvProduction,
  386.  
  387.                                 // If an error happens in a package, it's possible to be
  388.                                 // because it was compiled. Thus, we don't want the browser
  389.                                 // debugger to show the original code. Instead, the code
  390.                                 // being evaluated would be much more helpful.
  391.                                 sourceMaps: false,
  392.                             },
  393.                         },
  394.                         // "postcss" loader applies autoprefixer to our CSS.
  395.                         // "css" loader resolves paths in CSS and adds assets as dependencies.
  396.                         // "style" loader turns CSS into JS modules that inject <style> tags.
  397.                         // In production, we use MiniCSSExtractPlugin to extract that CSS
  398.                         // to a file, but in development "style" loader enables hot editing
  399.                         // of CSS.
  400.                         // By default we support CSS Modules with the extension .module.css
  401.                         {
  402.                             test: cssRegex,
  403.                             exclude: [cssModuleRegex, path.resolve(__dirname, 'src/SourceResolver/')],
  404.                             use: getStyleLoaders({
  405.                                 importLoaders: 1,
  406.                                 modules: true,
  407.                                 localIdentName: '[name]__[local]___[hash:base64:5]',
  408.                                 sourceMap: isEnvProduction && shouldUseSourceMap,
  409.                             }),
  410.                             // Don't consider CSS imports dead code even if the
  411.                             // containing package claims to have no side effects.
  412.                             // Remove this when webpack adds a warning or an error for this.
  413.                             // See https://github.com/webpack/webpack/issues/6571
  414.                             sideEffects: true,
  415.                         },
  416.                         // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
  417.                         // using the extension .module.css
  418.                         {
  419.                             test: cssModuleRegex,
  420.                             exclude: [path.resolve(__dirname, 'src/SourceResolver/')],
  421.                             use: getStyleLoaders({
  422.                                 importLoaders: 1,
  423.                                 sourceMap: isEnvProduction && shouldUseSourceMap,
  424.                                 modules: true,
  425.                                 getLocalIdent: getCSSModuleLocalIdent,
  426.                             }),
  427.                         },
  428.                         // Opt-in support for SASS (using .scss or .sass extensions).
  429.                         // By default we support SASS Modules with the
  430.                         // extensions .module.scss or .module.sass
  431.                         {
  432.                             test: sassRegex,
  433.                             exclude: [sassModuleRegex, path.resolve(__dirname, 'src/SourceResolver/')],
  434.                             use: getStyleLoaders(
  435.                                 {
  436.                                     importLoaders: 2,
  437.                                     sourceMap: isEnvProduction && shouldUseSourceMap,
  438.                                 },
  439.                                 'sass-loader'
  440.                             ),
  441.                             // Don't consider CSS imports dead code even if the
  442.                             // containing package claims to have no side effects.
  443.                             // Remove this when webpack adds a warning or an error for this.
  444.                             // See https://github.com/webpack/webpack/issues/6571
  445.                             sideEffects: true,
  446.                         },
  447.                         // Adds support for CSS Modules, but using SASS
  448.                         // using the extension .module.scss or .module.sass
  449.                         {
  450.                             test: sassModuleRegex,
  451.                             exclude: [path.resolve(__dirname, 'src/SourceResolver/')],
  452.                             use: getStyleLoaders(
  453.                                 {
  454.                                     importLoaders: 2,
  455.                                     sourceMap: isEnvProduction && shouldUseSourceMap,
  456.                                     modules: true,
  457.                                     getLocalIdent: getCSSModuleLocalIdent,
  458.                                 },
  459.                                 'sass-loader'
  460.                             ),
  461.                         },
  462.                         // "file" loader makes sure those assets get served by WebpackDevServer.
  463.                         // When you `import` an asset, you get its (virtual) filename.
  464.                         // In production, they would get copied to the `build` folder.
  465.                         // This loader doesn't use a "test" so it will catch all modules
  466.                         // that fall through the other loaders.
  467.                         {
  468.                             loader: require.resolve('file-loader'),
  469.                             // Exclude `js` files to keep "css" loader working as it injects
  470.                             // its runtime that would otherwise be processed through "file" loader.
  471.                             // Also exclude `html` and `json` extensions so they get processed
  472.                             // by webpacks internal loaders.
  473.                             exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/, path.resolve(__dirname, 'src/SourceResolver/')],
  474.                             options: {
  475.                                 name: 'static/media/[name].[hash:8].[ext]',
  476.                             },
  477.                         },
  478.                         // ** STOP ** Are you adding a new loader?
  479.                         // Make sure to add the new loader(s) before the "file" loader.
  480.                     ],
  481.                 },
  482.             ],
  483.         },
  484.         plugins: [
  485.             // Generates an `index.html` file with the <script> injected.
  486.             new HtmlWebpackPlugin(
  487.                 Object.assign(
  488.                     {},
  489.                     {
  490.                         inject: true,
  491.                         template: paths.appHtml,
  492.                     },
  493.                     isEnvProduction
  494.                         ? {
  495.                             minify: {
  496.                                 removeComments: true,
  497.                                 collapseWhitespace: true,
  498.                                 removeRedundantAttributes: true,
  499.                                 useShortDoctype: true,
  500.                                 removeEmptyAttributes: true,
  501.                                 removeStyleLinkTypeAttributes: true,
  502.                                 keepClosingSlash: true,
  503.                                 minifyJS: true,
  504.                                 minifyCSS: true,
  505.                                 minifyURLs: true,
  506.                             },
  507.                         }
  508.                         : undefined
  509.                 )
  510.             ),
  511.             // Inlines the webpack runtime script. This script is too small to warrant
  512.             // a network request.
  513.             isEnvProduction &&
  514.             shouldInlineRuntimeChunk &&
  515.             new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime~.+[.]js/]),
  516.             // Makes some environment variables available in index.html.
  517.             // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  518.             // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  519.             // In production, it will be an empty string unless you specify "homepage"
  520.             // in `package.json`, in which case it will be the pathname of that URL.
  521.             // In development, this will be an empty string.
  522.             new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  523.             // This gives some necessary context to module not found errors, such as
  524.             // the requesting resource.
  525.             new ModuleNotFoundPlugin(paths.appPath),
  526.             // Makes some environment variables available to the JS code, for example:
  527.             // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  528.             // It is absolutely essential that NODE_ENV is set to production
  529.             // during a production build.
  530.             // Otherwise React will be compiled in the very slow development mode.
  531.             new webpack.DefinePlugin(env.stringified),
  532.             // This is necessary to emit hot updates (currently CSS only):
  533.             isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
  534.             // Watcher doesn't work well if you mistype casing in a path so we use
  535.             // a plugin that prints an error when you attempt to do this.
  536.             // See https://github.com/facebook/create-react-app/issues/240
  537.             isEnvDevelopment && new CaseSensitivePathsPlugin(),
  538.             // If you require a missing module and then `npm install` it, you still have
  539.             // to restart the development server for Webpack to discover it. This plugin
  540.             // makes the discovery automatic so you don't have to restart.
  541.             // See https://github.com/facebook/create-react-app/issues/186
  542.             isEnvDevelopment &&
  543.             new WatchMissingNodeModulesPlugin(paths.appNodeModules),
  544.             isEnvProduction &&
  545.             new MiniCssExtractPlugin({
  546.                 // Options similar to the same options in webpackOptions.output
  547.                 // both options are optional
  548.                 filename: 'static/css/[name].[contenthash:8].css',
  549.                 chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
  550.             }),
  551.             // Generate a manifest file which contains a mapping of all asset filenames
  552.             // to their corresponding output file so that tools can pick it up without
  553.             // having to parse `index.html`.
  554.             new ManifestPlugin({
  555.                 fileName: 'asset-manifest.json',
  556.                 publicPath: publicPath,
  557.                 generate: (seed, files) => {
  558.                     const manifestFiles = files.reduce(function (manifest, file) {
  559.                         manifest[file.name] = file.path;
  560.                         return manifest;
  561.                     }, seed);
  562.  
  563.                     return {
  564.                         files: manifestFiles,
  565.                     };
  566.                 },
  567.             }),
  568.             // Moment.js is an extremely popular library that bundles large locale files
  569.             // by default due to how Webpack interprets its code. This is a practical
  570.             // solution that requires the user to opt into importing specific locales.
  571.             // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  572.             // You can remove this if you don't use Moment.js:
  573.             new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  574.             // Generate a service worker script that will precache, and keep up to date,
  575.             // the HTML & assets that are part of the Webpack build.
  576.             isEnvProduction &&
  577.             new WorkboxWebpackPlugin.GenerateSW({
  578.                 clientsClaim: true,
  579.                 exclude: [/\.map$/, /asset-manifest\.json$/],
  580.                 importWorkboxFrom: 'cdn',
  581.                 navigateFallback: publicUrl + '/index.html',
  582.                 navigateFallbackBlacklist: [
  583.                     // Exclude URLs starting with /_, as they're likely an API call
  584.                     new RegExp('^/_'),
  585.                     // Exclude URLs containing a dot, as they're likely a resource in
  586.                     // public/ and not a SPA route
  587.                     new RegExp('/[^/]+\\.[^/]+$'),
  588.                 ],
  589.             }),
  590.             // TypeScript type checking
  591.             useTypeScript &&
  592.             new ForkTsCheckerWebpackPlugin({
  593.                 typescript: resolve.sync('typescript', {
  594.                     basedir: paths.appNodeModules,
  595.                 }),
  596.                 async: isEnvDevelopment,
  597.                 useTypescriptIncrementalApi: true,
  598.                 checkSyntacticErrors: true,
  599.                 resolveModuleNameModule: process.versions.pnp
  600.                     ? `${ __dirname }/pnpTs.js`
  601.                     : undefined,
  602.                 resolveTypeReferenceDirectiveModule: process.versions.pnp
  603.                     ? `${ __dirname }/pnpTs.js`
  604.                     : undefined,
  605.                 tsconfig: paths.appTsConfig,
  606.                 reportFiles: [
  607.                     '**',
  608.                     '!**/__tests__/**',
  609.                     '!**/?(*.)(spec|test).*',
  610.                     '!**/src/setupProxy.*',
  611.                     '!**/src/setupTests.*',
  612.                 ],
  613.                 watch: paths.appSrc,
  614.                 silent: true,
  615.                 // The formatter is invoked directly in WebpackDevServerUtils during development
  616.                 formatter: isEnvProduction ? typescriptFormatter : undefined,
  617.             }),
  618.         ].filter(Boolean),
  619.         // Some libraries import Node modules but don't use them in the browser.
  620.         // Tell Webpack to provide empty mocks for them so importing them works.
  621.         node: {
  622.             module: 'empty',
  623.             dgram: 'empty',
  624.             dns: 'mock',
  625.             fs: 'empty',
  626.             http2: 'empty',
  627.             net: 'empty',
  628.             tls: 'empty',
  629.             child_process: 'empty',
  630.         },
  631.         // Turn off performance processing because we utilize
  632.         // our own hints via the FileSizeReporter
  633.         performance: false,
  634.     };
  635. };
Add Comment
Please, Sign In to add comment