github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/shyftBlockExplorerUI/config/webpack.config.prod.js (about)

     1  'use strict';
     2  
     3  const autoprefixer = require('autoprefixer');
     4  const path = require('path');
     5  const webpack = require('webpack');
     6  const HtmlWebpackPlugin = require('html-webpack-plugin');
     7  const ExtractTextPlugin = require('extract-text-webpack-plugin');
     8  const ManifestPlugin = require('webpack-manifest-plugin');
     9  const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
    10  const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
    11  const eslintFormatter = require('react-dev-utils/eslintFormatter');
    12  const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
    13  const paths = require('./paths');
    14  const getClientEnvironment = require('./env');
    15  
    16  // Webpack uses `publicPath` to determine where the app is being served from.
    17  // It requires a trailing slash, or the file assets will get an incorrect path.
    18  const publicPath = paths.servedPath;
    19  // Some apps do not use client-side routing with pushState.
    20  // For these, "homepage" can be set to "." to enable relative asset paths.
    21  const shouldUseRelativeAssetPaths = publicPath === './';
    22  // Source maps are resource heavy and can cause out of memory issue for large source files.
    23  const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
    24  // `publicUrl` is just like `publicPath`, but we will provide it to our app
    25  // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
    26  // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
    27  const publicUrl = publicPath.slice(0, -1);
    28  // Get environment variables to inject into our app.
    29  const env = getClientEnvironment(publicUrl);
    30  
    31  // Assert this just to be safe.
    32  // Development builds of React are slow and not intended for production.
    33  if (env.stringified['process.env'].NODE_ENV !== '"production"') {
    34    throw new Error('Production builds must have NODE_ENV=production.');
    35  }
    36  
    37  // Note: defined here because it will be used more than once.
    38  const cssFilename = 'static/css/[name].[contenthash:8].css';
    39  
    40  // ExtractTextPlugin expects the build output to be flat.
    41  // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
    42  // However, our output is structured with css, js and media folders.
    43  // To have this structure working with relative paths, we have to use custom options.
    44  const extractTextPluginOptions = shouldUseRelativeAssetPaths
    45    ? // Making sure that the publicPath goes back to to build folder.
    46      { publicPath: Array(cssFilename.split('/').length).join('../') }
    47    : {};
    48  
    49  // This is the production configuration.
    50  // It compiles slowly and is focused on producing a fast and minimal bundle.
    51  // The development configuration is different and lives in a separate file.
    52  module.exports = {
    53    // Don't attempt to continue if there are any errors.
    54    bail: true,
    55    // We generate sourcemaps in production. This is slow but gives good results.
    56    // You can exclude the *.map files from the build during deployment.
    57    devtool: shouldUseSourceMap ? 'source-map' : false,
    58    // In production, we only want to load the polyfills and the app code.
    59    entry: [require.resolve('./polyfills'), paths.appIndexJs],
    60    output: {
    61      // The build folder.
    62      path: paths.appBuild,
    63      // Generated JS file names (with nested folders).
    64      // There will be one main bundle, and one file per asynchronous chunk.
    65      // We don't currently advertise code splitting but Webpack supports it.
    66      filename: 'static/js/[name].[chunkhash:8].js',
    67      chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    68      // We inferred the "public path" (such as / or /my-project) from homepage.
    69      publicPath: publicPath,
    70      // Point sourcemap entries to original disk location (format as URL on Windows)
    71      devtoolModuleFilenameTemplate: info =>
    72        path
    73          .relative(paths.appSrc, info.absoluteResourcePath)
    74          .replace(/\\/g, '/'),
    75    },
    76    resolve: {
    77      // This allows you to set a fallback for where Webpack should look for modules.
    78      // We placed these paths second because we want `node_modules` to "win"
    79      // if there are any conflicts. This matches Node resolution mechanism.
    80      // https://github.com/facebookincubator/create-react-app/issues/253
    81      modules: ['node_modules', paths.appNodeModules].concat(
    82        // It is guaranteed to exist because we tweak it in `env.js`
    83        process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    84      ),
    85      // These are the reasonable defaults supported by the Node ecosystem.
    86      // We also include JSX as a common component filename extension to support
    87      // some tools, although we do not recommend using it, see:
    88      // https://github.com/facebookincubator/create-react-app/issues/290
    89      // `web` extension prefixes have been added for better support
    90      // for React Native Web.
    91      extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
    92      alias: {
    93        
    94        // Support React Native Web
    95        // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
    96        'react-native': 'react-native-web',
    97      },
    98      plugins: [
    99        // Prevents users from importing files from outside of src/ (or node_modules/).
   100        // This often causes confusion because we only process files within src/ with babel.
   101        // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
   102        // please link the files into your node_modules/ and let module-resolution kick in.
   103        // Make sure your source files are compiled, as they will not be processed in any way.
   104        new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
   105      ],
   106    },
   107    module: {
   108      strictExportPresence: true,
   109      rules: [
   110        // TODO: Disable require.ensure as it's not a standard language feature.
   111        // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
   112        // { parser: { requireEnsure: false } },
   113  
   114        // First, run the linter.
   115        // It's important to do this before Babel processes the JS.
   116        {
   117          test: /\.(js|jsx|mjs)$/,
   118          enforce: 'pre',
   119          use: [
   120            {
   121              options: {
   122                formatter: eslintFormatter,
   123                eslintPath: require.resolve('eslint'),
   124                
   125              },
   126              loader: require.resolve('eslint-loader'),
   127            },
   128          ],
   129          include: paths.appSrc,
   130        },
   131        {
   132          // "oneOf" will traverse all following loaders until one will
   133          // match the requirements. When no loader matches it will fall
   134          // back to the "file" loader at the end of the loader list.
   135          oneOf: [
   136            // "url" loader works just like "file" loader but it also embeds
   137            // assets smaller than specified size as data URLs to avoid requests.
   138            {
   139              test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
   140              loader: require.resolve('url-loader'),
   141              options: {
   142                limit: 10000,
   143                name: 'static/media/[name].[hash:8].[ext]',
   144              },
   145            },
   146            // Process JS with Babel.
   147            {
   148              test: /\.(js|jsx|mjs)$/,
   149              include: paths.appSrc,
   150              loader: require.resolve('babel-loader'),
   151              options: {
   152                
   153                compact: true,
   154              },
   155            },
   156            // The notation here is somewhat confusing.
   157            // "postcss" loader applies autoprefixer to our CSS.
   158            // "css" loader resolves paths in CSS and adds assets as dependencies.
   159            // "style" loader normally turns CSS into JS modules injecting <style>,
   160            // but unlike in development configuration, we do something different.
   161            // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
   162            // (second argument), then grabs the result CSS and puts it into a
   163            // separate file in our build process. This way we actually ship
   164            // a single CSS file in production instead of JS code injecting <style>
   165            // tags. If you use code splitting, however, any async bundles will still
   166            // use the "style" loader inside the async code so CSS from them won't be
   167            // in the main CSS file.
   168            {
   169              test: /\.css$/,
   170              loader: ExtractTextPlugin.extract(
   171                Object.assign(
   172                  {
   173                    fallback: {
   174                      loader: require.resolve('style-loader'),
   175                      options: {
   176                        hmr: false,
   177                      },
   178                    },
   179                    use: [
   180                      {
   181                        loader: require.resolve('css-loader'),
   182                        options: {
   183                          importLoaders: 1,
   184                          modules: true,
   185                          localIdentName: '[name]__[local]__[hash:base64:5]',
   186                          minimize: true,
   187                          sourceMap: shouldUseSourceMap,
   188                        },
   189                      },
   190                      {
   191                        loader: require.resolve('postcss-loader'),
   192                        options: {
   193                          // Necessary for external CSS imports to work
   194                          // https://github.com/facebookincubator/create-react-app/issues/2677
   195                          ident: 'postcss',
   196                          plugins: () => [
   197                            require('postcss-flexbugs-fixes'),
   198                            autoprefixer({
   199                              browsers: [
   200                                '>1%',
   201                                'last 4 versions',
   202                                'Firefox ESR',
   203                                'not ie < 9', // React doesn't support IE8 anyway
   204                              ],
   205                              flexbox: 'no-2009',
   206                            }),
   207                          ],
   208                        },
   209                      },
   210                    ],
   211                  },
   212                  extractTextPluginOptions
   213                )
   214              ),
   215              // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
   216            },
   217            // "file" loader makes sure assets end up in the `build` folder.
   218            // When you `import` an asset, you get its filename.
   219            // This loader doesn't use a "test" so it will catch all modules
   220            // that fall through the other loaders.
   221            {
   222              loader: require.resolve('file-loader'),
   223              // Exclude `js` files to keep "css" loader working as it injects
   224              // it's runtime that would otherwise processed through "file" loader.
   225              // Also exclude `html` and `json` extensions so they get processed
   226              // by webpacks internal loaders.
   227              exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
   228              options: {
   229                name: 'static/media/[name].[hash:8].[ext]',
   230              },
   231            },
   232            // ** STOP ** Are you adding a new loader?
   233            // Make sure to add the new loader(s) before the "file" loader.
   234          ],
   235        },
   236      ],
   237    },
   238    plugins: [
   239      // Makes some environment variables available in index.html.
   240      // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
   241      // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
   242      // In production, it will be an empty string unless you specify "homepage"
   243      // in `package.json`, in which case it will be the pathname of that URL.
   244      new InterpolateHtmlPlugin(env.raw),
   245      // Generates an `index.html` file with the <script> injected.
   246      new HtmlWebpackPlugin({
   247        inject: true,
   248        template: paths.appHtml,
   249        minify: {
   250          removeComments: true,
   251          collapseWhitespace: true,
   252          removeRedundantAttributes: true,
   253          useShortDoctype: true,
   254          removeEmptyAttributes: true,
   255          removeStyleLinkTypeAttributes: true,
   256          keepClosingSlash: true,
   257          minifyJS: true,
   258          minifyCSS: true,
   259          minifyURLs: true,
   260        },
   261      }),
   262      // Makes some environment variables available to the JS code, for example:
   263      // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
   264      // It is absolutely essential that NODE_ENV was set to production here.
   265      // Otherwise React will be compiled in the very slow development mode.
   266      new webpack.DefinePlugin(env.stringified),
   267      // Minify the code.
   268      new webpack.optimize.UglifyJsPlugin({
   269        compress: {
   270          warnings: false,
   271          // Disabled because of an issue with Uglify breaking seemingly valid code:
   272          // https://github.com/facebookincubator/create-react-app/issues/2376
   273          // Pending further investigation:
   274          // https://github.com/mishoo/UglifyJS2/issues/2011
   275          comparisons: false,
   276        },
   277        mangle: {
   278          safari10: true,
   279        },
   280        output: {
   281          comments: false,
   282          // Turned on because emoji and regex is not minified properly using default
   283          // https://github.com/facebookincubator/create-react-app/issues/2488
   284          ascii_only: true,
   285        },
   286        sourceMap: shouldUseSourceMap,
   287      }),
   288      // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
   289      new ExtractTextPlugin({
   290        filename: cssFilename,
   291      }),
   292      // Generate a manifest file which contains a mapping of all asset filenames
   293      // to their corresponding output file so that tools can pick it up without
   294      // having to parse `index.html`.
   295      new ManifestPlugin({
   296        fileName: 'asset-manifest.json',
   297      }),
   298      // Generate a service worker script that will precache, and keep up to date,
   299      // the HTML & assets that are part of the Webpack build.
   300      new SWPrecacheWebpackPlugin({
   301        // By default, a cache-busting query parameter is appended to requests
   302        // used to populate the caches, to ensure the responses are fresh.
   303        // If a URL is already hashed by Webpack, then there is no concern
   304        // about it being stale, and the cache-busting can be skipped.
   305        dontCacheBustUrlsMatching: /\.\w{8}\./,
   306        filename: 'service-worker.js',
   307        logger(message) {
   308          if (message.indexOf('Total precache size is') === 0) {
   309            // This message occurs for every build and is a bit too noisy.
   310            return;
   311          }
   312          if (message.indexOf('Skipping static resource') === 0) {
   313            // This message obscures real errors so we ignore it.
   314            // https://github.com/facebookincubator/create-react-app/issues/2612
   315            return;
   316          }
   317          console.log(message);
   318        },
   319        minify: true,
   320        // For unknown URLs, fallback to the index page
   321        navigateFallback: publicUrl + '/index.html',
   322        // Ignores URLs starting from /__ (useful for Firebase):
   323        // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
   324        navigateFallbackWhitelist: [/^(?!\/__).*/],
   325        // Don't precache sourcemaps (they're large) and build asset manifest:
   326        staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
   327      }),
   328      // Moment.js is an extremely popular library that bundles large locale files
   329      // by default due to how Webpack interprets its code. This is a practical
   330      // solution that requires the user to opt into importing specific locales.
   331      // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
   332      // You can remove this if you don't use Moment.js:
   333      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
   334    ],
   335    // Some libraries import Node modules but don't use them in the browser.
   336    // Tell Webpack to provide empty mocks for them so importing them works.
   337    node: {
   338      dgram: 'empty',
   339      fs: 'empty',
   340      net: 'empty',
   341      tls: 'empty',
   342      child_process: 'empty',
   343    },
   344  };