您的位置:首页 > Web前端 > React

webpack压缩react

2017-01-24 21:03 369 查看
Writing a web application in React using the ES6 awesomeness and spiced up with Webpack has
got to be very close to the perfect project for any web developer. This stack has been all the buzz lately, but it comes with a caveat —- the built output is gigantic!


Default Weback Project Build

Our example project is a React 0.14 web application utilizing ECMAScript 6 with a Babel 6 transpilation step through Webpack. You can simply clone
the initial setup or run
npm i react react-dom --save
npm i babel babel-core babel-loader babel-preset-es2015
babel-preset-react webpack --save-dev


These are all the necessary basics. Make sure you also have Webpack installed globally, which comes with the useful Webpack CLI
npm -g i webpack>


Now that you’re all set with dependencies, we’ll create the code for our Hello World application
import React from 'react';
import ReactDom from 'react-dom';

ReactDom.render((
Hello
), document.getElementById('root'));

index.js is the starting point of our hello world app

As for default Webpack configuration we’ll use the following code:
path = require('path');
const webpack = require('webpack');

module.exports = {
devtool: 'eval',
entry: './index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel']
}
],
},
};


webpack.config.js – Webpack default development configuration file

The Webpack configuration above is fairly standard and simple. It will transpile all JavaScript code with Babel and output it to the dist/bundle.js file.

Using the Webpack CLI, we will create our first build.
$> webpack --progress -p

Hash: 765639c3ef5551b2b6da
Version: webpack 1.12.3
Time: 3028ms
Asset    Size  Chunks             Chunk Names
bundle.js  704 kB       0  [emitted]  main
+ 159 hidden modules


Our Hello World build is a staggering 704 kB in size! Yes, my sentiments exactly!

We just established our baseline; creating the simplest of React applications using ECMAScript 6 and building it with Webpack yields a huge JavaScript file. Our goal is to shrink that down as much as possible.


Production Configuration Update #1: Source Maps

Webpack is primarily a tool for developers. As such, it offers a wide variety of settings that help with debugging code. One such configuration option, 
devtool
,
determines how and where the app stores source maps.

It’s common to see 
devtool: ‘eval’
 which is one of the fastest ways to
build apps with most of the development code information bundled in the output. While that’s really nice for development purposes, we will want to get rid of any unnecessary data in a production build.

There are a few production-ready options to go with, and we’ll go with 
cheap-module-source-map
(instead
of 
eval
) to minimize the output. Repeat the Webpack build to see how
much we gained (or hopefully, lost).
$> webpack --progress -p
Hash: a6ef587aedfce940104d
Version: webpack 1.12.3
Time: 5115ms
Asset       Size  Chunks             Chunk Names
bundle.js     189 kB       0  [emitted]  main
bundle.js.map  170 bytes       0  [emitted]  main
+ 159 hidden modules


Would you believe that we just shaved off 75% of the build output size? The newly created bundle.js is just 189kB (compared to the original 704kB). The newly introduced bundle.js.map
source map file is minimal and should be omitted in production.

This was already a significant improvement, but we can do better. Let’s see how we can improve the file size even more.


Production Configuration Update #2: Node Environment

Part of the 189kB bundle consists of various test helpers, which is another thing you don’t need in your production build. We can get rid of those if we tell Webpack to use the production node environment.

To do that, we will have to define a custom Webpack plugin. Don’t worry, that’s much easier than it sounds:
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],


Here, we simply created a 
NODE_ENV
 key in the 
process.env
 object
with value 
‘“production”’
associated with it. Webpack’s build process
will take this information and work out the magic all on it’s own. Let’s have a look.
$> webpack --progress -p
Hash: 39d00df29c750675828d
Version: webpack 1.12.3
Time: 4974ms
Asset       Size  Chunks             Chunk Names
bundle.js     131 kB       0  [emitted]  main
bundle.js.map  156 bytes       0  [emitted]  main
+ 154 hidden modules


Wow, the new bundle is now 131 kB. It may not look as dramatic as the improvement we made in the previous step, but it’s still a phenomenal 30% decrease in size.

Just two simple configuration changes lead us to 82% savings in the output size.

Given that the original React 0.14.2 framework weighs in at 135
kB, Webpack did a fantastic job atreducing the size of our transpiled ES6 source code to just 131 kB.


Conclusion

Webpack is a terrific tool that helps developers on so many fronts. We just learned that optimizing for production is painless and effective.

While we focused on React in the example above, surely this technique will prove fruitful in yourAngular apps as well. Give Webpack a chance and let me know how it went.

Also if you have other optimization ideas to share, please do so in the comments.

Finally, special thanks to Espen Hovlandsdal (@rexxars) who helped immensely with
his Webpack tips and ideas.

Source repository: https://github.com/ModusCreateOrg/webpack-react-es6-production-optimization
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: