How can I npm install
a package into a different directory?
Asked
Active
Viewed 5.4k times
2 Answers
153
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

Vincent
- 3,191
- 3
- 29
- 35
-
6How do you then get specific dependencies to use a package alias? I'm trying to upgrade from material UI 0.x to 4.x in an existing app. I need React 16.3 for 0.x and 16.8 for 4.x – Greg K Sep 27 '19 at 11:23
-
2Is it possible to install a package that has multiple names? – Mathias Lykkegaard Lorenzen Mar 16 '20 at 18:02
-
1Thank you so much for including the syntax for the `package.json` - every other answer I came across neglects this. – Slbox Apr 29 '20 at 01:21
-
This is brilliant! We used that to force a browserified version of dependencies of react-pdf/renderer package, in context where we cannot do it using Webpack aliases – Eric Burel Mar 18 '22 at 07:46
-
This is a cool approach, but one drawback I noticed is that sometimes after running `npm install` the package version gets updated in `package-lock.json`. Is there a way to avoid that? – szx Jun 24 '22 at 20:23
-
1@szx Specify `1.5.3` not `^1.5.3`. More on semver: https://stackoverflow.com/a/25861938/121240 https://docs.npmjs.com/cli/v8/configuring-npm/package-json#dependencies – Vincent Jun 30 '22 at 01:04
2
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

Akshay Vijay Jain
- 13,461
- 8
- 60
- 73