DEV Community

Imed Jaberi
Imed Jaberi

Posted on

How to install multiple versions of a npm package at the same time/project

Have you encountered when you are working on a project and you want to upgrade a dependency but you can’t do because you will have to migrate a lot of code or you should test your project with multi-versions of some module(s)?

Personally, I make and maintain a lot of Koa modules. Sometimes, I need to make the modules work with all versions of Koa so this is a real example how i do to solve this problem.

I found a solution by use a custom alias when installing a package with npm or yarn.

Alias allows you to install multiple versions of a same package in the same project.

You can use the alias by following this command:

with npm

npm i <your-alias>@npm:<package-name>
Enter fullscreen mode Exit fullscreen mode

with yarn

yarn add <your-alias>@npm:<package-name>
Enter fullscreen mode Exit fullscreen mode

When you want to install a specific version of the package append the command with @<package-version>.

Read the npm documentation here and/or yarn here to find more about alias.

For example, we want to use Koa with release 1.x.x and the latest one 2.x.x.

with npm

npm i koa-v1@npm:koa@1
npm i koa@npm:koa
Enter fullscreen mode Exit fullscreen mode

with yarn

yarn add koa-v1@npm:koa@1
yarn add koa@npm:koa
Enter fullscreen mode Exit fullscreen mode

Now, when you import the Koa module using koa-v1, it means that you are using koa@1.x.x. Otherwise, when importing with koa, it means that you are using the latest version of koa@ 2.x.x.

Did I miss something? Let me know in the comment section and let’s work on that.

Thank you for reading. I hope this will help you on your journey! ❤️

Top comments (4)

Collapse
 
antmik profile image
Anton

Thank you for the article. It helped me a lot in the current project

Collapse
 
bennycode profile image
Benny Code

Very cool trick indeed! It helped me a lot today as I needed features from a beat API while still wanting to use the stable legacy API for most of the other parts. 👍

Collapse
 
mikhail_ivlev_2942bef3ecb profile image
Mikhail Ivlev

I have error with that alias
Error: Unsatisfied version 3.2.0 from lk-desktop-host of shared singleton module new-chat (required =npm:@support/chat-react@3.2.0)
In devDependencies i have
"new-chat": "=npm:@support/chat-react@3.2.0",

Collapse
 
mikhail_ivlev_2942bef3ecb profile image
Mikhail Ivlev

to resolve my issue i added in module-federation in the field shared an object
{
'@support/chat-react': {
singleton: true,
strictVersion: true,
requiredVersion: '3.2.0',
}
}