Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does npm scripts prioritise local dependency over global ones?

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?

like image 930
Chris Avatar asked Jun 07 '17 18:06

Chris


People also ask

When does the NPM prepare script run?

These scripts happen in addtion to the "pre" and "post" script. NOTE: If a package being installed through git contains a prepare script, its dependencies and devDependencies will be installed, and the prepare script will be run, before the package is packaged and installed. Runs BEFORE the package is prepared and packed, ONLY on npm publish.

What is the difference between local and global npm packages?

local packages are installed in the directory where you run npm install <package-name>, and they are put in the node_modules folder under this directory global packages are all put in a single place in your system (exactly where depends on your setup), regardless of where you run npm install -g <package-name>

What is prepublish in NPM?

Since [email protected], the npm CLI has run the prepublish script for both npm publish and npm install, because it's a convenient way to prepare a package for use (some common use cases are described in the section below). It has also turned out to be, in practice, very confusing.

How do npm packages run?

Package scripts run in an environment where many pieces of information are made available regarding the setup of npm and the current state of the process. If you depend on modules that define executable scripts, like test suites, then those executables will be added to the PATH for executing the scripts.


1 Answers

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.

like image 96
Andrea Carraro Avatar answered Sep 22 '22 21:09

Andrea Carraro