How to install NPM package under alias or different name

NpmAliasNpm Install

Npm Problem Overview


How can I npm install a package into a different directory?

Npm Solutions


Solution 1 - Npm

Say you want to install Case package, you can have a specific version under an alias:

npm i case-1.5.3@npm:case@1.5.3

or just give it a different name

npm i kool@npm:case

If you want to edit package.json directly:

"dependencies": {
  "case-1.5.3": "npm:case@^1.5.3",
  "kool": "npm:case@^1.6.1"
}

require():

let Case = require( 'case-1.5.3' );
let Kool = require( 'kool' );

Yarn used to have this functionality for a long time, and npm finally got it since v6.9.0, Mar 2019.

If you want to update your npm:

sudo npm i -g npm@latest

Solution 2 - Npm

with PNPM
if want to use two different versions of a package in your project. It is possible with following commands

pnpm add <any-alias-name>@npm:package-name

for example 

pnpm add new-lodash@npm:lodash@2
pnpm add old-lodash@npm:lodash@1

Now we can use both lodash in our project

const newLodash = require('new-lodash');
const oldLodash = require('old-lodash');

Note that it worked only for require and not for ESM import statement i.e.

import oldLodash from 'old-lodash' // will throw error

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVincentView Question on Stackoverflow
Solution 1 - NpmVincentView Answer on Stackoverflow
Solution 2 - NpmAkshay Vijay JainView Answer on Stackoverflow