Install 2 versions of the same npm package


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

Problem

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

npm install react-dom@15 react-dom@16 --save

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.

Solution

  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 react-dom@15 --save --exact
    
  3. Create a Git repository and push it to GitHub:
    git init && git push -u
    
  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.



Please support this site and join our Discord!