List Npm Scripts

| Comments

Tools for storing and then later easily running scripts alias names are awesome. Npm is one of those tools. Rake is another. Rake has a cool feature of allowing you to list the scripts available to you. Npm has not – until now.

npm

Npm Scripts

You can specify scripts in your package.json for later use. They go in the scripts attribute:

package.json
1
2
3
4
5
6
{
  "scripts": {
    "start": "node server.js",
    "dist": "webpack -p"
  }
}

To run these scripts, you use the npm run command. For example, type npm run build to actually execute the webpack -p command in your terminal. start and test are specially commands to npm and do not require run. Instead, you can use npm start.

Npm List Scripts

In Rake, you run rake -T in your terminal and all the available scripts for your project are displayed. This allows you to see the what’s potentially helpful. You can’t be expected to remember all of them, especially months later, right?

I certainly was having a hard time remembering all of my scripts and getting tired of typing cat package.json. It didn’t feel as cool as the rake -T experience. I wrote a library called npm-ls-scripts. To install, run:

1
npm install npm-ls-scripts -g

I like installing this package globally because then the CLI binary is available globally – it does seem applicable to all projects. You could instead include it under project devDependencies if you’d like.

If installed globally, you can then run it with:

1
ls-scripts

If I was to run this in the above project, it would print:

1
2
3
4
5
NPM - ls scripts
---
start - node server.js
dist - webpack -p
---

This prints the exact code that can be executed for each script. If I would like to add some prose around any or all of the available scripts, I can do so by adding more config data to my package.json that will print when I run ls-scripts:

package.json
1
2
3
4
5
6
7
{
  "config": {
    "scripts: {
       "dist": "Builds project for distribution"
    }
  }
}

Now if I were to run the ls-scripts command, I would see:

1
2
3
4
5
NPM - ls scripts
---
start - node server.js
dist - Builds project for distribution
---

Cool, right? Complete with Shakespearean prose.

New: Npm Run

After I had developed the above npm-ls-scripts tool, Npm built this feature natively into the core tool – finally! Now, to list available scripts, the command is intuitively to leave off the target script and instead simply type:

1
npm run

On the above example, this would yield:

1
2
3
4
5
Available scripts in the package:
  start
    node server.js
  dist
    webpack -p

So, they work about the same, and now it’s built in! What other cool features could you imagine this having?

Comments