Chameera Dulanga

4 strong reasons to start learning Webpack in-depth today

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?

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.

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.

Load More Related Articles
Load More By john
Load More In Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *