Modern web applications are not just about developing core functionalities. We also should pay attention to factors like application performance, development productivity, and efficiency to get the maximum out of our effort.
But, are you aware that you can use Webpack to address some of these challenges?
However, just knowing how Webpack works won’t be enough to get maximum from it. So, let’s see what you can achieve by being an expert in Webpack.
As developers, we always like to see faster feedback while we carry out modifications to the code. Besides, there are various methods we follow.
If you know the Webpack well, you can easily enable its Hot Module Replacement feature to improve the development process.
Hot module replacement (HMR) allows us to modify modules while it is in the running state. Since HMR prevents full reload of the application, it will remain in the same state and will only update what is changed.
All you need is to update the webpack-dev-server configuration and use its built-in HMR plugin.
....
module.exports = {
entry: {
app: './src/index.js',
},
...
devServer: {
contentBase: './dist',
hot: true, // <--- Add this line
},
plugins: [
...
new HtmlWebpackPlugin({
title: 'Hot Module Replacement',
}),
],
output: {
...
},
};
Pro tip: HMR becomes very handy in situations where you develop web applications for multiple device form factors. E.g., You can access the development server URL on both desktop and mobile and instantly see how it looks in both.
If your project has a significant amount of dead code or a large number of shared libraries, it’s common to experience a long application loading time. It is common to see tree-shaking in such situations to avoid dead or unwanted code from bundling.
....
module.exports = {
entry: {
app: './src/index.js',
},
output: {
...
},
//add below line
mode: 'development',
optimization: {
usedExports: true,
},
};
But, how can we guarantee that Webpack makes the correct decision about unused codes in the project?
For example, it’s common to have global level stylesheets imported to the project, and usually, those files aren’t used anywhere. But removing such files can affect the whole project.
Webpack uses a special configuration in package.json
file named sideEffects
. By default, all the files in your project are considered files with side effects, and tree shaking won’t be performed.
However, we can manually change this behavior by changing
sideEffects
value to false, true or providing an array with file names.
// All files have side effects "sideEffects": true// No files have side effects
"sideEffects": false//Only these files have side effects,
"sideEffects": [
"./src/file1.js",
"./src/file2.js"
]
}
If you enable tree-shaking in Webpack configuration, ensure to include files that don’t have side effects in package.json
file settings.