Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js / npm - override local default modules directory (node_modules)

Let's say I don't want to install my local (per project) packages in node_modules - I'd like to have it under sources/node_modules instead of just node_modules. Is it possible to override it just like you can do in bower?

In bower you provide .bowerrc file with directory option, see docs. It works exactly as if you had bower_components locally - no additional files, loaders, nothing at all - just the container dir is different.

like image 329
ducin Avatar asked May 09 '26 03:05

ducin


1 Answers

tl;dr

$ mkdir -p sources
$ ln -s package.json sources/package.json
$ npm install --prefix sources/
$ export NODE_PATH="`pwd`/sources"

Explanation

You can (as @adeneo mentioned) simply install packages to any folder with:

$ npm install --prefix sources/ my-package

This will install to sources/my-package. However, this solution is far from neat in two ways:

package.json

It sounds as though, rather than installing individual packages, what you really want to do is install everything in package.json to the sources/ folder. The problem is that when you do npm install --prefix sources/, it also looks for package.json in the sources/ folder. If that works for you, then great.

The only way I've found to keep your package.json in your project root and install node modules somewhere else is to symlink the local package.json into that directory:

$ mkdir -p sources
$ ln -s package.json sources/package.json
$ npm install --prefix sources

require

As you mentioned, you will probably want your scripts to be able to require modules like normal - require('my-module') rather than require('sources/my-module').

The NODE_PATH environment variable can help here:

$ export NODE_PATH=`pwd`/sources/node_modules
$ node -e "require('my-module')"  # Success

There is an important caveat: node will look for modules in a specific order:

  1. In a node_modules folder in the local directory
  2. In a node_modules folder in the parent directory, then its parent etc.
  3. In paths in the NODE_PATH, if it hasn't found the module yet

So be careful there are aren't any other node_modules folders in the current or any parent directory which mention your modules, or things could get quite confusing.

like image 75
Robin Winslow Avatar answered May 11 '26 17:05

Robin Winslow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!