What are npm scripts and how to use them ? The script property of Package.json

About

The scripts property in package.json are command lines that:

They are also known as npm scripts because npm is historically the first package manager.

An Hello World Example

{
    "scripts": {
        "world": "echo hello world",
    }
}
  • Run it
yarn world
# or 
npm world
  • output from yarn
yarn run v1.22.19
$ echo hello world
hello world
Done in 0.13s.

Management

Run

Command line

To run a script, you would execute the following npm command

yarn scriptName
# or
npm run scriptName

All

To run the script sequentially on all platform. https://www.npmjs.com/package/npm-run-all

Example with the release script:

"scripts": {
    "build": "cross-env NODE_ENV=production webpack --mode 'production'",
    "test": "jest",
    "publish": "npm publish",
    "release": "npm-run-all test build publish",
}

VsCode

From the VsCode IDE in a VsCode - Task (tasks.json)

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558 
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "npm",
            "script": "test",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Shortcut (Alias)

  • npm test is a shortcut for npm run test
  • npm start is a shortcut for npm run start

Search path

The execution depends on your package manager. You should check the documentation for the run command. For example for yarn.

Otherwise, generally, the search path is modified for the duration of the run.

Within scripts, you can reference locally installed npm packages by name instead of writing out the entire path. This convention is the standard in most npm-based projects and allows for instance to directly call a package. Example:

  • myApp,
  • instead of ./node_modules/.bin/myApp

Documentation / Reference





Discover More
Javascript - npm (Node package manager)

Npm is the package manager that is packaged/installed with a node installation. Automatically, with a node installation. Manually: -{VERSION}.tgz To update...
Javascript Package - Package.json

Package.json is used by npm to store metadata for projects published as package. The package.json files: * serves as documentation for what packages your project depends on. * allows you to specify...
Card Puncher Data Processing
VsCode - Task (tasks.json)

tasks.json file in the workspace .vscode folder Ctrl+Shift+B (Run Build Task) Terminal > Configure Tasks > Create tasks.json file from templates > Others See ...



Share this page:
Follow us:
Task Runner