Webpack is one of the most popular tools for bundling front-end assets. It has been around for a long time and has evolved with the web development ecosystem. In October 2020, webpack 5 was released with many improvements and new features. In this post, we will explore some of the highlights of webpack 5 and how they can benefit your projects.
One of the main goals of webpack 5 was to improve the build performance by leveraging persistent caching. This means that webpack can store some of the intermediate results of the compilation process on disk and reuse them in subsequent builds. This can significantly reduce the build time, especially for large projects with many modules and dependencies.
To enable persistent caching, you need to add a cache option to your webpack configuration file:
module.exports = {
// ...
cache: {
type: 'filesystem', // use filesystem for persistent caching
buildDependencies: {
config: [__filename], // include the configuration file as a build dependency
},
},
};
The cache option tells webpack to use the filesystem as the cache type and to invalidate the cache when the configuration file changes. You can also customize other aspects of the caching behavior, such as the cache directory, the cache name, or the cache expiration. For more details, see the documentation.
Another goal of webpack 5 was to improve the long-term caching of the generated bundles by using better algorithms and defaults. Long-term caching refers to the ability of browsers to cache static assets for a long time and reuse them across multiple visits. This can improve the loading performance and user experience of your web applications.
Webpack 5 introduces several changes that can enhance the long-term caching of your bundles:
To take advantage of these features, you need to configure your output filenames to include content hashes:
module.exports = {
// ...
output: {
filename: '[name].[contenthash].js', // use content hash for main chunks
chunkFilename: '[name].[contenthash].js', // use content hash for split chunks
},
};
You can also customize other aspects of the output filenames, such as the length or format of the hashes. For more details, see the documentation.
Webpack 5 also made some changes to its internal structures and compatibility with web platforms. These changes may not be visible to users directly, but they can improve the quality and maintainability of webpack itself.
Some of these changes are:
For more details on these changes, see the changelog.
Webpack 5 is a major update that brings many improvements and new features to one of the most popular bundlers for front-end assets. It focuses on enhancing the performance, caching, quality
Vite or Webpack: Which One is Faster and Better for Your Vue Project?
What do you think?