Run NPM scripts in Visual Studio Code with a Single Click

Recently, I wondered if there is a possibility not having to remember the NPM script names in my package.json and to start them faster without having to open a terminal and typing npm run <script-name> every time. It turns out there is a solution!

NPM defines a lot of predefined scripts and CLI commands which you can run with npm <command>, for example npm install or npm test.

For user-defined scripts, you have to use npm run <script-name>, such as npm run test-all. If no command is provided, it lists all available scripts

"scripts": { 
   "test": "mocha --opts mocha.opts \"./tests/test.spec.ts\"", 
   "test-all": "mocha --opts mocha.opts \"./tests/*.spec.ts\""

In this example, I used wildcards to run all my spec.files in a certain directory.

However, during the daily development routine, I had to run these script by hand so often, I searched for a faster and more convenient solution.

Start your scripts faster in VS Code

You have several ways to start one of the script commands defined in your package.json.

The first is to open a terminal in VS Code with Terminal -> New Terminal (CTRL+Shift+ö).

Thereby, the terminal is conveniently started in your project’s working directory. You can simply run your script with npm run my-script.

The second even more convenient option is to go to File -> Preferences -> Settings (CTRL+,) and to enable npm.enableScriptExplorer.

VS Code will now automatically search for your package.json file and extract all commands from its scripts section.

Enable NPM script command detection

This adds a new view in the sidebar on the left called “NPM Scripts”.

Your NPM scripts in the new sidebar view

There, all NPM script commands are listed and you can simply click on the little arrow next to each one to start it.

A new terminal is opened and the script is executed.

VS Code automatically runs the selected script