Guest User

My Webpack `create-react-app` Configuration

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