SHARE
TWEET

webpack.config.js

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