Can I change where npm installs local packages?

I’m trying to figure out if there’s a way to tell npm to put local packages somewhere other than the default node_modules folder. Is there some kind of command or setting I can use to make npm install stuff in a different spot?

For example, I want my packages to go in vendor/node_modules instead of just node_modules in the current folder. I’ve looked around but can’t find a clear answer on how to do this. Does anyone know if it’s possible and how to set it up?

Here’s what I’ve tried so far:

npm install some-package
npm install --prefix ./vendor some-package

But neither of these put the package where I want. Any ideas on how to make this work? Thanks!

Although npm doesn’t offer a native option to change the local installation directory, there is a workaround that has worked for me. You can adjust the npm configuration by creating a .npmrc file in the project root and setting the prefix to point to your custom directory, for example, vendor/node_modules. Then, establish a symbolic link from the default node_modules folder to your chosen directory. This allows npm to operate normally while storing files elsewhere. Be cautious of potential compatibility issues with scripts expecting the usual directory layout and thoroughly test your setup first.

I’ve grappled with this issue before, and while npm doesn’t make it straightforward, there’s a way to achieve what you’re after. Instead of messing with npm’s default behavior, I’ve found success using a package.json script to handle custom installation locations. Here’s what I do:

  1. In package.json, add a custom install script:
    “scripts”: {
    “custom-install”: “npm install --prefix ./vendor”
    }

  2. Run npm run custom-install some-package

This approach keeps your main npm commands intact while giving you the flexibility to install packages in a custom location when needed. It’s been a lifesaver for projects with specific directory structures. Just remember to update your .gitignore and any build processes to account for the new location.

hey mate, u can actually use the --prefix flag with npm install, but it’s a bit tricky. Try runnin this:

npm install --prefix ./vendor some-package

then add a symlink from node_modules to vendor/node_modules. might need to fiddle w/ it, but should work. good luck!