Use Webpack 5 with Angular version 11
Monday, November 9, 2020
Use Webpack 5 with Angular version 11
The Angular command-line interface (CLI) uses webpack for bundling JavaScript, as well as the webpack dev server for local development.
Angular version 11 will still use webpack version 4, however, you can use webpack 5 using yarn's selective dependency resolutions feature, or installing the npm-force-resolutions pacakge. Selective dependency resolution enables developers to specificy custom package transitive dependency (in other words dependencies of dependencies) versions.
NPM
If you are using npm, you need to first install the npm-force-resolutions package:
npm i npm-force-resolutions
Then, you need to modify your package.json scripts to include a preinstall hook:
"scripts": {
"preinstall": "npx npm-force-resolutions"
},
Yarn or NPM
If you are using either Yarn or npm you can now update the transitive dependency resolution version using the resolutions
property in the package.json file:
{
"resolutions": {
"webpack": "^5.0.0"
},
}
Finally, install webpack version 5 via Yarn with yarn install
or with npm via npm install
.
Instructions
Consider using Webpack 5 with Angular version 11
Using the npm-force-resolutions package if you are reluctant to use yarn over npm
Webpack 5 supports module federation, better tree shaking, improved caching, and more.
Code Examples
Specify webpack version 5 resolution in package.json file
"resolutions": {
"webpack": "^5.0.0"
},
Have a question or comment?
For me and my college it didn't work wir yarn. With yarn the auto-refresh stopped working completely.
Juri, when you say the "auto-refresh stopped working" are you referring to the
--watch
mode in which the CLI will rebuild on a file change?I tried all possible options for live reload without success when I'm using yarn. I also tried yarn2 without success.
So I just refused using webpack 5.x.x and removed
preinstall
andresolutions
frompackage.json
. It's not recommended for productive use any way currently according to https://blog.angular.io/version-11-of-angular-now-available-74721b7952f7.I also removed
node_modules
and reinstalled them with yarn2. And I'm happy now. Live reload works and hmr too. I have changed from npm to yarn2. So I'm twice happy now.Note! For angular cli to work with yarn2 you have to put the following entry to
.yarnrc.yml
:nodeLinker: "node-modules"
according to https://yarnpkg.com/configuration/yarnrc.Using webpack 5 with npm install in give some error:- Cannot find webpack module