javascriptnpmyarnpkgbowerc3.js

How to manage multiple versions of the same NPM dependency?


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.


What I've considered so far


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