Advertisement
ikkew

webpack.config.prod.js

Mar 9th, 2018
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. var autoprefixer = require('autoprefixer');
  4. var webpack = require('webpack');
  5. var HtmlWebpackPlugin = require('html-webpack-plugin');
  6. var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
  7. var getClientEnvironment = require('./env');
  8. var paths = require('./paths');
  9. var path = require('path');
  10.  
  11. var ExtractTextPlugin = require('extract-text-webpack-plugin');
  12. var ManifestPlugin = require('webpack-manifest-plugin');
  13. var appPackageJson = require(paths.appPackageJson);
  14.  
  15. // Webpack uses `publicPath` to determine where the app is being served from.
  16. // It requires a trailing slash, or the file assets will get an incorrect path.
  17. var publicPath = paths.servedPath;
  18. // Some apps do not use client-side routing with pushState.
  19. // For these, "homepage" can be set to "." to enable relative asset paths.
  20. var shouldUseRelativeAssetPaths = publicPath === './';
  21. // `publicUrl` is just like `publicPath`, but we will provide it to our app
  22. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  23. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  24. var publicUrl = publicPath.slice(0, -1);
  25. // Get environment variables to inject into our app.
  26. var env = getClientEnvironment(publicUrl);
  27.  
  28. // Assert this just to be safe.
  29. // Development builds of React are slow and not intended for production.
  30. if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  31.   throw new Error('Production builds must have NODE_ENV=production.');
  32. }
  33.  
  34. // Note: defined here because it will be used more than once.
  35. const cssFilename = 'css/[name].[contenthash:8].css';
  36.  
  37. // ExtractTextPlugin expects the build output to be flat.
  38. // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
  39. // However, our output is structured with css, js and media folders.
  40. // To have this structure working with relative paths, we have to use custom options.
  41. const extractTextPluginOptions = shouldUseRelativeAssetPaths
  42.   // Making sure that the publicPath goes back to to build folder.
  43.   ? { publicPath: Array(cssFilename.split('/').length).join('../') }
  44.   : undefined;
  45.  
  46. // This is the production configuration.
  47. // It compiles slowly and is focused on producing a fast and minimal bundle.
  48. // The development configuration is different and lives in a separate file.
  49. module.exports = {
  50.   // Don't attempt to continue if there are any errors.
  51.   bail: true,
  52.   // We generate sourcemaps in production. This is slow but gives good results.
  53.   // You can exclude the *.map files from the build during deployment.
  54.   devtool: 'source-map',
  55.   // In production, we only want to load the polyfills and the app code.
  56.   entry: {
  57.     app: [
  58.       require.resolve('./polyfills'),
  59.       paths.appIndexJs
  60.     ],
  61.     'vendor': Object.keys(appPackageJson.dependencies),
  62.     'appsettings': [require.resolve('../src/constants/appsettings.json')]  
  63.   },
  64.   output: {
  65.     // The build folder.
  66.     path: paths.appBuild,
  67.     // Generated JS file names (with nested folders).
  68.     // There will be one main bundle, and one file per asynchronous chunk.
  69.     // We don't currently advertise code splitting but Webpack supports it.
  70.     filename: 'js/[name].[chunkhash:8].js',
  71.     chunkFilename: 'js/[name].[chunkhash:8].chunk.js',
  72.     // We inferred the "public path" (such as / or /my-project) from homepage.
  73.     publicPath: publicPath
  74.   },
  75.   resolve: {
  76.     // This allows you to set a fallback for where Webpack should look for modules.
  77.     // We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
  78.     // We use `fallback` instead of `root` because we want `node_modules` to "win"
  79.     // if there any conflicts. This matches Node resolution mechanism.
  80.     // https://github.com/facebookincubator/create-react-app/issues/253
  81.     fallback: paths.nodePaths,
  82.     // These are the reasonable defaults supported by the Node ecosystem.
  83.     // We also include JSX as a common component filename extension to support
  84.     // some tools, although we do not recommend using it, see:
  85.     // https://github.com/facebookincubator/create-react-app/issues/290
  86.     extensions: ['.js', '.json', '.jsx', '.sass', '.scss', ''],
  87.     root: paths.appSrc,
  88.     alias: {
  89.       // Support React Native Web
  90.       // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  91.       'react-native': 'react-native-web'
  92.     }
  93.   },
  94.   module: {
  95.     // First, run the linter.
  96.     // It's important to do this before Babel processes the JS.
  97.     preLoaders: [
  98.       {
  99.         test: /\.(js|jsx)$/,
  100.         loader: 'eslint',
  101.         include: paths.appSrc
  102.       }
  103.     ],
  104.     loaders: [
  105.       // ** ADDING/UPDATING LOADERS **
  106.       // The "url" loader handles all assets unless explicitly excluded.
  107.       // The `exclude` list *must* be updated with every change to loader extensions.
  108.       // When adding a new loader, you must add its `test`
  109.       // as a new entry in the `exclude` list in the "url" loader.
  110.  
  111.       // "url" loader embeds assets smaller than specified size as data URLs to avoid requests.
  112.       // Otherwise, it acts like the "file" loader.
  113.       {
  114.         exclude: [
  115.           /\.html$/,
  116.           /\.(js|jsx)$/,
  117.           /(\.css|\.scss)$/,
  118.           /\.json$/,
  119.           /\.svg$/
  120.         ],
  121.         loader: 'url',
  122.         query: {
  123.           limit: 10000,
  124.           name: 'media/[name].[hash:8].[ext]'
  125.         }
  126.       },
  127.       // Process JS with Babel.
  128.       {
  129.         test: /\.(js|jsx)$/,
  130.         include: paths.appSrc,
  131.         loader: 'babel',
  132.       },
  133.       // The notation here is somewhat confusing.
  134.       // "postcss" loader applies autoprefixer to our CSS.
  135.       // "css" loader resolves paths in CSS and adds assets as dependencies.
  136.       // "style" loader normally turns CSS into JS modules injecting <style>,
  137.       // but unlike in development configuration, we do something different.
  138.       // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
  139.       // (second argument), then grabs the result CSS and puts it into a
  140.       // separate file in our build process. This way we actually ship
  141.       // a single CSS file in production instead of JS code injecting <style>
  142.       // tags. If you use code splitting, however, any async bundles will still
  143.       // use the "style" loader inside the async code so CSS from them won't be
  144.       // in the main CSS file.
  145.       {
  146.         test: /(\.css|\.scss)$/,
  147.         loader: ExtractTextPlugin.extract(
  148.           'style-loader',
  149.           'css-loader?importLoaders=1!postcss-loader!sass-loader',
  150.           extractTextPluginOptions
  151.         )
  152.         // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
  153.       },
  154.       // JSON is not enabled by default in Webpack but both Node and Browserify
  155.       // allow it implicitly so we also enable it.
  156.       {
  157.         test: /\.json$/,
  158.         loader: 'json'
  159.       },
  160.       // "file" loader for svg
  161.       {
  162.         test: /\.svg$/,
  163.         loader: 'file',
  164.         query: {
  165.           name: 'media/[name].[hash:8].[ext]'
  166.         }
  167.       },
  168.       {
  169.         test: require.resolve("jquery"),
  170.         loader: "expose-loader?$!expose-loader?jQuery"
  171.       }
  172.       // ** STOP ** Are you adding a new loader?
  173.       // Remember to add the new extension(s) to the "url" loader exclusion list.
  174.     ],
  175.   },
  176.  
  177.   // We use PostCSS for autoprefixing only.
  178.   postcss: function() {
  179.     return [
  180.       autoprefixer({
  181.         browsers: [
  182.           '>1%',
  183.           'last 4 versions',
  184.           'Firefox ESR',
  185.           'not ie < 9', // React doesn't support IE8 anyway
  186.         ]
  187.       }),
  188.     ];
  189.   },
  190.   plugins: [
  191.     // Makes some environment variables available in index.html.
  192.     // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  193.     // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  194.     // In production, it will be an empty string unless you specify "homepage"
  195.     // in `package.json`, in which case it will be the pathname of that URL.
  196.     new InterpolateHtmlPlugin(env.raw),
  197.     // Generates an `index.html` file with the <script> injected.
  198.     new HtmlWebpackPlugin({
  199.       title: 'Emmy Kassa',
  200.       inject: true,
  201.       template: paths.appHtml,
  202.       minify: {
  203.         removeComments: true,
  204.         collapseWhitespace: true,
  205.         removeRedundantAttributes: true,
  206.         useShortDoctype: true,
  207.         removeEmptyAttributes: true,
  208.         removeStyleLinkTypeAttributes: true,
  209.         keepClosingSlash: true,
  210.         minifyJS: true,
  211.         minifyCSS: true,
  212.         minifyURLs: true
  213.       }
  214.     }),
  215.     // Makes some environment variables available to the JS code, for example:
  216.     // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  217.     // It is absolutely essential that NODE_ENV was set to production here.
  218.     // Otherwise React will be compiled in the very slow development mode.
  219.     new webpack.DefinePlugin(env.stringified),
  220.     // This helps ensure the builds are consistent if source hasn't changed:
  221.     new webpack.optimize.OccurrenceOrderPlugin(),
  222.     // Try to dedupe duplicated modules, if any:
  223.     new webpack.optimize.DedupePlugin(),
  224.     // Minify the code.
  225.     new webpack.optimize.UglifyJsPlugin({
  226.       compress: {
  227.         screw_ie8: true, // React doesn't support IE8
  228.         warnings: false
  229.       },
  230.       mangle: {
  231.         screw_ie8: true
  232.       },
  233.       output: {
  234.         comments: false,
  235.         screw_ie8: true
  236.       }
  237.     }),
  238.     new webpack.optimize.CommonsChunkPlugin({
  239.       names: ['appsettings'],
  240.       chunks: ['appsettings']
  241.     }),
  242.     new webpack.optimize.CommonsChunkPlugin({
  243.       names: ['vendor', 'manifest'],
  244.       minChunks: Infinity,
  245.     }),
  246.     // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
  247.     new ExtractTextPlugin(cssFilename),
  248.     // Generate a manifest file which contains a mapping of all asset filenames
  249.     // to their corresponding output file so that tools can pick it up without
  250.     // having to parse `index.html`.
  251.     new ManifestPlugin({
  252.       fileName: 'asset-manifest.json'
  253.     }),
  254.     new webpack.ProvidePlugin({
  255.       $: 'jquery',
  256.       jQuery: 'jquery',
  257.       jquery: 'jquery'
  258.     })
  259.   ],
  260.   // Some libraries import Node modules but don't use them in the browser.
  261.   // Tell Webpack to provide empty mocks for them so importing them works.
  262.   node: {
  263.     fs: 'empty',
  264.     net: 'empty',
  265.     tls: 'empty'
  266.   }
  267. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement