Kayote
Kayote

Reputation: 15627

NPM - Scripts - How Do They Work?

I cant get my head around how scripts are running within package.json & would appreciate some insight for us newbies.

Is it the case that they are bash scripts that are run by node having loaded the various dependencies?

If yes, then how does it process the javascript code?

Upvotes: 2

Views: 767

Answers (2)

georg
georg

Reputation: 214959

Is it the case that they are bash scripts

yes

that are run by node

no, they are run by sh.

having loaded the various dependencies?

no, no js files are loaded, the only thing npm does for you is to prepare the environment. Among other things, it adds ./node_modules/.bin to PATH so you can invoke installed modules immediately.

When you run npm run-script whatever, this is what npm does:

  • reads the corresponding command line from package.json
  • prepares the environment
  • invokes sh (or comspec on win) and gives it the command and the env. No big magic here.

Upvotes: 3

Paul Stoner
Paul Stoner

Reputation: 1512

This may not be 100% accurate so I implore other, more qualifies, experts to chime in.

NPM is a program, installed as part of the Node.JS environment. It's two main uses (as describe here) are for searching for node.js packages and installing node.js packages.

However, NPM is also capable of understanding "simple" (a relative term) scripts.

When you write a script in your package.json, and issue the NPM command, say "npm start", NPM will read and interpret the script. NPM then searches your node_modules structure for the accompanying binary and executes that binary with the necessary start parameters.

An example would be

"test": "mocha --reporter spec test"

when you issue "npm test", NPM will look for the mocha binary in your node_modules structure. NPM finds mocha initiates the call, passing the reporter command arg (--reporter spec) and the name of the file to be read and executed for the test.

Upvotes: 0

Related Questions