DEV Community

Guido Zambarda
Guido Zambarda

Posted on • Originally published at iamguidozam.blog on

Use multiple version of an NPM package

I was wondering how to use two different package version in the same project, maybe you’re wondering why I would do such a thing but picture this:

You have a public NPM package and you want to update some of your controls that use an external package, but to avoid a breaking change you want to keep the existing implementation and alongside create a new implementation based on the updated version of the external package, let’s say a Version 2 of your controls.

So, this is possible and, I would say, pretty straight forward using an alias.

To install an NPM package using an alias you can use the following generic formula:

npm i <package_alias>@npm:<package_name>@<version>
Enter fullscreen mode Exit fullscreen mode

In detail:

  • package_alias: this will be the alias to be used when importing the external control.
  • package_name: the actual name of the external package.
  • version: the specific version to install, if not specified will be the more recent one.

For example, if you want to install two versions of the lodash package you can use the following command:

npm i lodash-old@npm:lodash@3.10.1 lodash-new@npm:lodash@4.17.15
Enter fullscreen mode Exit fullscreen mode

This will create two aliases:

  • lodash-old: that references the lodash package version 3.10.1
  • lodash-new: that references the lodash package version 4.17.15

And then you can use the following code to import the two packages pin a control:

import * as _old from 'lodash-old';
import * as _ from 'lodash-new';
Enter fullscreen mode Exit fullscreen mode

And here is how to use multiple version of a package in a solution!


Bonus tip: if you want some help while writing code it would be best to import the types package. To remain on the previous example and import the types packages for lodash you can use the following code:

npm install --save-dev @types/lodash-old@npm:@types/lodash@3.10.9 @types/lodash-new@npm:@types/lodash@4.14.202
Enter fullscreen mode Exit fullscreen mode

If you want to check out a very ugly sample you can find it here.

Hope this helps!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay