When we develop, we often use a combination of Visual Studio Code (VSCode), Node.js, and NPM. Let’s see how to configure VSCode to work with NPM Scripts.
In the software development process, it’s common to have a series of scripts defined in the package.json
file of our project. These scripts allow us to automate tasks such as compilation, testing, and other development-related actions.
We can run these scripts from the command line or configure Visual Studio Code to launch them from the graphical interface. Let’s see how we can start these scripts from Visual Studio Code.
Run from the VSCode terminal
The most obvious way to start a script command defined in the package.json
file is to use the terminal in VS Code. To do this, you can go to the “Terminal” tab and select “New Terminal” (CTRL+Shift+ñ).
The terminal will open in your project’s working directory. Now, we simply invoke the script by doing this. You can just use the command to run the desired script.
npm run script_name
NPM Command Explorer
There is a much easier option to launch NPM scripts from the VSCode user interface. An option that, for some reason, in the latest versions of VSCode is disabled by default.
To enable this option, go to File -> Preferences -> Settings (CTRL+,) and enable the option npm.enableScriptExplorer.
Once enabled, VS Code will automatically look for the package.json file in your project and extract all the commands defined in the scripts section.
By enabling this option, we will be able to add a new sidebar called NPM Scripts
(which again, I don’t know why it’s not enabled by default).
In this view, all NPM script commands will be listed, and you can start them simply by clicking the small arrow next to each one.
When you click on a command, a new terminal will open, and the corresponding script will be executed.
VS Code will automatically take care of executing the selected script, saving us the hassle of opening a terminal manually and typing the command.
This is how easily you can launch NPM scripts from the package.json
file in VS Code, comfortably and without the need to press a single key in the terminal.