Optimization techniques

It is important to notice that, in all the examples in this book, we are using apps that have either been created with create-react-app or have been created from scratch, but always with the development version of React.

Using the development version of React is very useful for coding and debugging as it gives you all the necessary information to fix the various issues. However, all the checks and warnings come with a cost, which we want to avoid in production.

So, the very first optimization that we should do to our applications is to build the bundle, setting the NODE_ENV environment variable to production. This is pretty easy with webpack and it is just a matter of using DefinePlugin in the following way:

  new webpack.DefinePlugin({ 
'process.env': {
NODE_ENV: JSON.stringify('production')
    } 
})

To achieve the best performance, we not only want to create the bundle with the production flag activated, but we also want to split our bundles: one for our application and one for our node_modules. To do so, you need to use the new optimization node in webpack 4:

  optimization: {
splitChunks: {
cacheGroups: {
default: false,
commons: {
test: /node_modules/,
name: 'vendor',
chunks: 'all'
}
}
}
}

Now, webpack 4 has two modesā€”development and production. By default, the production mode is enabled, meaning the code will be minified and compressed when you compile your bundles using the production mode; you can specify it with this:

  {
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
}

Your webpack.config.js file should look like this:

  module.exports = {
entry: './index.js',
optimization: {
splitChunks: {
cacheGroups: {
default: false,
commons: {
test: /node_modules/,
name: 'vendor',
chunks: 'all'
}
}
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
],
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development'
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.81.240