npm scripts

npm can do much more than just installing packages and resolving dependencies for installing packages. One of the things it can do is running scripts! You might have seen that already:


npm test
npm start

It has a series of defaults. For example:

npm start

will attempt to run

node server.js

You can, of course, redefine those defaults by specifying them in the scripts field in package.json. Suppose my script for launching the server doesn't live in the root of the project, then I'd have to modify the start script entry consequently. Imagine this very minimal package.json:


{
  "scripts": {
    "start": "node server/main.js"
  }
}

The defaults can be called with just npm something, and there's a list of default scripts npm recognises in the script documentation page. Some are very handy because they get called automatically before some scripts are executed. For example, if you run npm test, the pre-test script will also be automatically run before (if it has been specified). You could use that to make sure your bundles are updated before testing them.

If you want to run a script whose key is not one of the defaults, you have to invoke it in a slightly different manner. Suppose it's specified here in your scripts:


{
  "scripts": {
    "my-specially-named-script": "echo \"NICE\""
  }
}

You would then run it with


npm run my-specially-named-script

As you can see it's not too complicated, and the whole thing is very minimal and obvious, which I like.

If you want to learn more about "advanced" uses of npm and scripts, be sure to read the excellent Task automation with npm run from the always inspiring substack.