Two Quick Ways To Reduce React App’s Size In Production

rajaraodv
rajaraodv
Nov 30, 2016 · 3 min read

1. Add the following Webpack plugins (source code)

plugins: [
new webpack.DefinePlugin({ // <-- key to reducing React's size
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.DedupePlugin(), //dedupe similar code
new webpack.optimize.UglifyJsPlugin(), //minify everything
new webpack.optimize.AggressiveMergingPlugin()//Merge chunks
],
File size Development v/s Production

2. Serve gzipped file in production

2.1 dynamic gzip (not preferred)

//Simply do this to add dynamic gzipping (not preferred)npm install compression --save //installvar compression = require(‘compression’); //import to express appapp.use(compression());//add this as the 1st middleware

2.2 Build time gzip (preferred)

1.Install the Webpack compression plugin 
npm install compression-webpack-plugin --save-dev

2. Import the plugin to webpack.config.prod.js
var CompressionPlugin = require('compression-webpack-plugin');
3. Add it to plugins array
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new CompressionPlugin({ <-- Add this
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
})

]
4. Finally, add this middleware to Express to return .js.gz so you can still load bundle.js from the html but will receive bundle.js.gzapp.get('*.js', function (req, res, next) {
req.url = req.url + '.gz';
res.set('Content-Encoding', 'gzip');
next();
});

My Other Posts

React Performance:

Functional Programming

ES6

WebPack

Draft.js

React And Redux :

Salesforce

rajaraodv

Written by

rajaraodv

Trying to make Web development simple. Former Developer Advocate @Salesforce, VMware (node.js); Engineer @ Yahoo, Zimbra. Twitter: @rajaraodv

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade