How to Create a Task to Run an NPM Script from package.json in VS Code using tasks.json

Share

In VS Code, it's possible to create a build task (or test task) to run an NPM script from your package.json using tasks.json. An example:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "run-npm-to-build-my-project",
            "detail": "Runs my build script from package.json",
            "type": "npm",
            "script": "build-my-project",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Understanding The Code

The label and detail keys are just random text we can use to identify and describe our task.

The type = npm key-value pair tells VS Code this task is an NPM script task, and script tells VS Code what script to run. In order for this to work, we must have a package.json containing code like this:

{
    "scripts": {
        "build-my-project": "webpack"
    }
}

This is equivalent to running npx webpack in the terminal.

This command allows you to run an arbitrary command from an npm package (either one installed locally, or fetched remotely), in a similar context as running it via npm run.

npx [https://docs.npmjs.com/cli/v8/commands/npx] (accessed 2024-11-22)

The isDefault option makes this task the default build task, so you can run it with the keyboard shortcut Ctrl+Shift+B. If this isn't intended, you can remove it.

The kind option tells VS Code what kind of task it is. Valid values are build, test, or none. This seems to have no purpose except letting VS Code filter which tasks to display in its GUI when you use "Run Build Task..." from the menubar without a default build task.

Comments

Leave a Reply

Leave your thoughts! Required fields are marked *