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.
Aliases
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.
Read the documentation on aliasing with npm here and yarn here.
How to use?
To install a package under an aliased name run:
npm install <alias>@npm:<name>
or
yarn add <alias>@npm:<name>
When you want to install a specific version of the package append the command with @<version>
.
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:react-helmet@5.2.1
npm install react-helmet@npm:react-helmet
or
yarn add react-helmet-old@npm:react-helmet@5.2.1
yarn add react-helmet@npm:react-helmet
Npm or yarn will now add two folders to your node_modules
folder, e.g. react-helmet
and react-helmet-old
, and lets you import from react-helmet-old
and react-helmet
in your project. Now you can start refactoring step by step.
Sidenote
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.
Conclusion
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!
Top comments (0)