Webpack 5 was released on Oct 2020. In the official release statement — https://webpack.js.org/blog/2020-10-10-webpack-5-release/, Webpack 5 has improvements in code generation and general tree shaking. Let’s try some basic tests to see if there is any difference between the generated packages.
First, let’s try to setup a single environment with both version of webpack. Although it will be easier to just have 2 separate setup installed with different version of webpack each.
npm i webpack --save-dev
The version I used is v5.12.1 and v4.44.2. I believe there will be differences from using different versions. Next we install Webpack 4 in a different package name.
npm i webpack4@npm:webpack@4.44.2
I also installed commonly used libraries such as @babel@7.12.10 (cli, core, preset-env, preset-react), babel-loader@8.2.2, react and react-dom@17.0.1, webpack-cli@4.3.1.
Using the default webpack’s packaging, I try packaging my basic Hello World React app.
There are challenges in running both webpack in the same environment. I will document it at the bottom of this article.
There are some slight differences, overally about 4KB less using Webpack 5. However, this is not a fair comparison as I think Webpack 5 uses Terser as the minimizer which extracts licenses into a separate file (as shown in the folder).
If you try opening the bundled file, you will see wasted space. This can be further optimized by using Terser plugin in Webpack 4 (npm i terser-webpack-plugin).
npm i terser-webpack-plugin@4.2.3
We get 3KB less or 2.3% less. However, the sample project is small and probably may achieve a better results with a larger web application. Next I test using an incomplete Single Page App (SPA) personal mini-project that I did in 2020.
It achieved a 7KB reduction or 1.7% reduction in size.
Conclusion
Through the quick tests, it shows that Webpack 5 does shave off a small amount of code and the amount perhaps will help as the app grow larger. May be interesting to experiment to see coding style code result in a smaller package.
Challenges
1. Running 2 versions of Webpack
To run 2 webpack versions in the same setup, I ran using the command webpack for v5 but had to create a separate script for v4.
Create a “webpack.runtime.js” within the root folder of the project which import webpack directly from node_modules folder. In package.json under scripts, run the javascript using node instead.
$> npm run build5
$> npm run build5
2. Two versions of Terser Plugin
Webpack 4 requires v4 of Terser Plugin. Although we can also install Terser under a different package, I encounter the below error while running.
If you dig into terser-webpack-plugin4/dist/index.js, you will discover that it is hardcoded to use the package webpack.
I know it is bad not edit the library directly. However, since this is not for anyone else, I made a quick switch in the code.
After the change, webpack v4 was able to execute smoothly. Nice.