Reduce webpack bundle size for production

Written by haochuan | Published 2017/10/27
Tech Story Tags: javascript | webpack | front-end-development | programming | react

TLDRvia the TL;DR App

No indroduction here, starting.

  1. Use the right environment variable

new webpack.DefinePlugin({‘process.env’: {‘NODE_ENV’: ‘production’}})

2. Use production parameter

webpack -p

3. Advanced uglification

new UglifyJSPlugin({// options})

4. Optimizing dependencies import

Instead of import the full dependency:

import _ from ‘lodash’;

Just import what you really need:

import _ from ‘lodash/core’;

5. Use Bundle Analyzer to figure out what increases the size

e.g. Most of the time we should ignore the moment locale files

new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)

6. Extract vendors out of your bundle

module.exports = {…,entry: {app: ‘./src/index.js’,vendor: [‘react’, ‘moment’, ‘lodash/core’]},…,plugins: […,new webpack.optimize.CommonsChunkPlugin({name: ‘vendor’})]};

7. Extract vendors out of your bundle

module.exports = {…,module: {rules: […,// css{test: /\.css$/,use: ExtractTextPlugin.extract({fallback: ‘style-loader’,use: [‘css-loader’]})}]},plugins: […,new ExtractTextPlugin(‘style.css’),]};

8. Code split by routes

Result per step on one of my project

See ya.


Published by HackerNoon on 2017/10/27