8

I understand npm scripts adds ./node_modules/.bin to your PATH, therefore you can simply run npm test using the package.json below, and npm will automagically use the local version of mocha found in ./node_modules/.bin

"scripts": {
    "test": "mocha"
}

This is a nice feature, because it saves me writing package.json files like this:

"scripts": {
    "test": "./node_modules/.bin/mocha"
}

BUT what if I bring on a new developer who has mocha installed globally? or I need to push this to an environment with preconfigured global packages? If I am using the short-hand mocha, rather than ./node_modules/.bin/mocha in my package.json, What takes precedence, the global or local package?

Chris
  • 392
  • 1
  • 4
  • 16

1 Answers1

8

Node.js will try to run first your locally installed packages.

If you require a module, Node.js looks for it by going through all node_modules/ directories in ancestor directories (./node_modules/, ../node_modules/, ../../node_modules/, etc.). The first appropriate module that is found is used.

For a more detailed explanation about how Node.js resolves required modules, here is a nice breakdown.

Andrea Carraro
  • 9,731
  • 5
  • 33
  • 57
  • Ok that looks promising, so `../../../../node_modules/` will always be the first appropriate module before `/usr/local/bin` (global) is checked. Sweet! thanks. – Chris Jun 08 '17 at 08:21