Install 2 versions of the same npm package


This article goes over how to install two or more versions of the same npm package.

Let’s say you want to install react-dom v15 and react-dom v16 in the same project:

However, package.json saves only 1 version:

{
  "name": "my-project",
  "dependencies": {
    "react-dom": "^16.13.1"
  }
}

This is because package names must be unique.

To go around this, you can do the following.

  1. In a new directory, initialize an npm package with a different name:
    $ mkdir ~/react-dom-core && cd ~/react-dom-core
    $ npm init --yes
    
  2. Install the dependency at the version you want:
    $ npm install [email protected] --save --exact
    
  3. Create a Git repository and push it to GitHub:
    $ git init
    $ git push
    
  4. Return to your original project and save the repository as a dependency:
    $ cd ~/my-project/
    $ npm install https://github.com/remarkablemark/react-dom-core --save
    

    Note: You can also install from a specific branch, tag, or commit.

Now your package.json will look like this:

{
  "name": "my-project",
  "dependencies": {
    "react-dom": "16",
    "react-dom-core": "git+https://github.com/remarkablemark/react-dom-core.git"
  }
}

This means you can import both dependencies in your Node.js module:

// index.js
const ReactDOM16 = require('react-dom');
const ReactDOM15 = require('react-dom-core');

You can even publish the package if the name isn’t taken.

See react-dom-core as an example.



If you enjoyed this post, please consider supporting this site!