Sometimes the API of an npm package changes. And sometimes the package is not backward compatible. In big projects, it is sometimes hard to refactor all the code concerned with a new API of an npm package you just updated. You probably want to be able to refactor this code step by step.
With npm or yarn, you can install a package under a custom alias. This enables you to install multiple versions of a package in the same project.
How to use?
To install a package under an aliased name run:
npm install <alias>@npm:<name>
yarn add <alias>@npm:<name>
When you want to install a specific version of the package append the command with
Using multiple versions of the same package
So for example, if you want to use multiple versions of the
react-helmet package run:
npm install react-helmet-old@npm:email@example.com npm install react-helmet@npm:react-helmet
yarn add react-helmet-old@npm:firstname.lastname@example.org yarn add react-helmet@npm:react-helmet
Npm or yarn will now add two folders to your
node_modules folder, e.g.
react-helmet-old, and lets you import from
react-helmet in your project. Now you can start refactoring step by step.
Not all packages support the usage of multiple versions side by side. For example, we tried to install two versions of
react-dnd for which you need to use a provider component which was changed in the newer version. The two providers collided when used together so we were forced to do the whole refactor at once.
Aliases are a convenient way to upgrade a package gradually. Although we couldn't use it in our specific use case maybe there are people out there who can!