How to manage multiple versions of the same NPM dependency?

Issue

Situation

I’ve written a bunch of D3.js charts using the latest version of D3 (4.9.1).

However I also need to include the occasional C3.js chart in my app, problem is- C3 requires D3 v3.5.0.

About the Project

My project uses the MEAN (with Angular 4) stack, and I’ve been using Bower to manage frontend dependencies.

What I’ve considered so far

  • Forking C3 to update it to the latest version of D3 (it’s not really feasible though)
  • Using a different package manager, such as Yarn
  • Just forgetting about C3…. (don’t want to do this, as it will involve a lot of re-work!)
  • Specifying a URL of an older version in the bower.json. However, I still was not able to reference to just that version for C3, and the latest for everything else.

    "d3": "^4.9.1",
    "d3-3.5.0": "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.0/d3.min.js"
    

Question

Is it possible to manage multiple versions of the same dependency, cleanly?
And if not, what would be a sensible work-around?

Solution

TLDR

Aliased versions of a dependency can be created with both NPM or Yarn using:

npm install <package_name_alias>@npm:<package_name>

Intro

Having multiple versions of the same dependency is really not ideal if it can be helped.
But if, for example you’re migrating to the latest version of a given package, while continuing to support legacy features in the interim, then it may be necessary.

Ensure you’re using a recent version of NPM (at least v6.9.0 when support for this was added).

Install

So, to for example install both Vue 2, and the latest Vue 3 with NPN package aliases, we would do:

npm i vue
npm i vue-legacy@npm:vue@2.6.14

Or, with Yarn:

yarn add vue
yarn add vue-legacy@npm:vue@2.6.14

Import

Then, when it comes time to use the dependency,

import Vue from 'vue'; // Will use the latest version
import Vue from 'vue-legacy'; // Will use V 2.6.14

Package.json

In the package.json, this will look like:

"dependencies": {
  "vue": "^3.2.33",
  "vue-legacy": "npm:vue@^2.6.14"
}

You can also add this into your package.json manually, remove the lock file, and run npm install / yarn to fetch

Alternate Sources

You can also install packages directly from GitHub using this method. Useful to get a specific version, even if not yet published to NPM, or if you wish to use your own fork of the project.

npm install package-name@github:username/repository

Answered By – Lissy93

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.