NPM must be used when developing with Node, and scripting is one of NPM’s strongest and most common features.

I’ll show you how to use NPM scripts in this article.

1. What is NPM script?

Npm allows you to define the script command package.json using the scripts field in the file.

    {
        // ...
        "scripts": {
            "build": "node build.js"
        }
 } Copy the code

The above code is part of the package.json file, where the field is an object. Each of its properties corresponds to a script. For example, the script corresponding to the build command is Node build.js.

If you NPM run use the command from the command line, the script will be executed.

    $ npm run build
    # equivalent to execution
    $ node build.js
Copy the code

These scripts defined in package.json are called NPM scripts. There are many advantages:

  • Project-related scripts can be placed in one place.
  • Script commands for different projects can use the same external interface as long as they have the same functionality. Users don’t need to know how to test your project, just run the NPM Run test.
  • You can take advantage of many of the accessibility features that NPM provides.

You can use the NPM run command with no arguments to view all NPM script commands for the current project.

    $ npm run
Copy the code

The principle of 2.

The principle of NPM scripts is very simple. Whenever NPM run is executed, a new shell is automatically created and the specified script commands are executed in that shell. Therefore, as long as the command can be run by a shell program (usually Bash), it can be written in NPM scripts.

In particular, subdirectories of the current node_modules/.bin directory are added to the PATH variable by the created shell NPM run, and the PATH variable is restored after execution.

This means that all scripts in the node_modules /.bin subdirectory of the current directory can be invoked directly by the script name, without adding a path. For example, if the dependencies of the current project contain Mocha, then simply write Mocha test directly:

    "test": "mocha test"
Copy the code

Instead of something like this:

    "test": "./node_modules/.bin/mocha test"
Copy the code

Since the only requirement for NPM scripts is that the scripts can be executed in the shell, they don’t have to be Node scripts, and any executable can be written in them.

The exit code for NPM scripts also follows the rules of shell scripts. If the exit code is not 0, NPM will assume that the script failed.

3. A wildcard

Because NPM scripts are Shell scripts, Shell wildcards can be used.

    "lint": "jshint *.js"
    "lint": "jshint **/*.js"
Copy the code

In the above code, * represents any file name and ** represents any subdirectory.

If you want to pass wildcards to the original command to prevent escape by the Shell, you must escape the asterisk.

    "test": "tap test/\*.js"
Copy the code

4. Pass parameters

Use — to indicate the parameters passed to the NPM script.

    "lint": "jshint **.js"
Copy the code

If you pass arguments to the above NPM run lint command, you must write the following.

    $ npm run lint --  --reporter checkstyle > checkstyle.xml
Copy the code

You can also rewrap the command package.json in.

    "lint": "jshint **.js".    "lint:checkstyle": "npm run lint -- --reporter checkstyle > checkstyle.xml"
Copy the code

5. Execution sequence

If you want to perform multiple tasks in an NPM script, you need to know the order in which they are executed.

If the execution is parallel (parallel parallel execution), the ampersand symbol can be used.

    $ npm run script1.js & npm run script2.js
Copy the code

This && symbol can be used if the execution is sequential (the next task is executed only if the previous one is successfully executed).

    $ npm run script1.js && npm run script2.js
Copy the code

These two symbols are a function of Bash. Alternatively, you can use the node’s task management modules: script-runner, npm-run-all, redrun.

6. The default value

Typically, NPM scripts are provided by users. However, NPM provides default values for both scripts. In other words, these two scripts can be used without definition.

    "start": "node server.js".    "install": "node-gyp rebuild"
Copy the code

In the above code, the default value NPM run start is Node server.js, which provides a server.js script at the root of the project; The default value NPM run install is node-gyp rebuild, as long as there is a file in the root directory of the binding.gyp project.

7. The hook

The NPM script has two hooks: pre and Post. For example, the hooks for build script commands are prebuild and postbuild.

    "prebuild": "echo I run before the build script".    "build": "cross-env NODE_ENV=production webpack".    "postbuild": "echo I run after the build script
Copy the code

When the user executes, it automatically executes the NPM Run build in the following order.

    npm run prebuild && npm run build && npm run postbuild
Copy the code

Therefore, some preparation and cleaning can be done in these two hooks. Here’s an example.

    "clean": "rimraf ./dist && mkdir dist".    "prebuild": "npm run clean".    "build": "cross-env NODE_ENV=production webpack"
Copy the code

Npm provides the following hooks by default:

  • Pre-release, post-release
  • Preinstall, post install
  • Preuninstall, postuninstall
  • Previous version, later version
  • Pre-test, post-test
  • Cross, back stop
  • Before startup, recording starts
  • Before reboot, after reboot

Custom script commands can also be added with pre and POST hooks. For example, the script command myscript has premyScript and postmyScript hooks. However, double pres and posts are invalid. For example, prepretest and postposttest are invalid.

The variable provided by NPM in nPM_lifecycle_event returns the name of the currently running script, such as pretest, test, posttest, etc. Therefore, you can use this variable to write code for different commands in the same script file of NPM scripts. Let’s look at the following example.


    const TARGET = process.env.npm_lifecycle_event;
    
    if (TARGET === 'test') {
          console.log('Running the test task! ');
 }   if (TARGET === 'pretest') {  console.log('Running the pretest task! ');  }   if (TARGET === 'posttest') {  console.log('Running the posttest task! ');  } Copy the code

Note that the prepublish hook will run not only before the NPM publish command, but also before the NPM install (without any parameters) command. However, this behavior can easily confuse users, so NPM 4 introduced a new hook, Prepublish, that behaves like prepare. As of NPM 5, the prepublish hook will only run before the NPM publish command.

8. Abbreviations

This is a short version of four commonly used NPM scripts.

  • NPM start is the short NPM run start
  • NPM stop is the short NPM run stop
  • NPM test is a short NPM run test
  • NPM restart is the short NPM run stop && NPM run restart && NPM run start

NPM start, NPM stop, and NPM restart are all well understood, and NPM restart is the compound command that actually executes the three script commands: stop, restart, start. And the order of execution is as follows.

  • Restart the
  • To mobilize
  • stop
  • Mail to stop
  • Start all over again
  • Pre start
  • start
  • Mail began to
  • After the restart

9. The variable

NPM scripts are very powerful and let you work with NPM internal variables.

First, the NPM script can get package.json fields prefixed with nPM_package_. For example, package.json below is one.

    {
        "name": "foo".        "version": "1.2.5".        "scripts": {
            "view": "node view.js"
 }  } Copy the code

The variable npM_package_name then returns foo, and the variable npM_package_version returns 1.2.5.

    // view.js
    console.log(process.env.npm_package_name); // foo
console.log(process.env.npm_package_version); / / 1.2.5Copy the code

In the above code, we get the field values of package.json from the environment variable process.env object. If it is a Bash script, you can use $npM_package_name and get the two values $npM_package_version.

The npM_package_ prefix also supports nested package.json fields.

    "repository": {
        "type": "git".        "url": "xxx"
    },
    scripts: {
 "view": "echo $npm_package_repository_type"  } Copy the code

In the code above, you can use the Type attribute of the get field. repositorynpm_package_repository_type

Here’s another example.

    "scripts": {
        "install": "foo.js"
    }
Copy the code

In the above code the value of the npm_package_scripts_install variable is equal to foo.js.

NPM config get XXX The NPM configuration variable (the value returned by the command) can also be obtained using the npm_config_ prefix. For example, you can use the RELEASE tag npM_CONFIG_TAG that gets the current module.

    "view": "echo $npm_config_tag".Copy the code

Note that environment variables can override the config object package.json in.

    { 
    "name" : "foo".    "config" : { "port" : "8080" },
    "scripts" : { "start" : "node server.js" }
    }
Copy the code

In the above code, the npM_package_config_port variable returns 8080. And you can override this value in the following way.

    $ npm config set foo:port 80
Copy the code

The env command lists all environment variables.

    "env": "env"
Copy the code

10. Common script examples


    // delete the directory
    "clean": "rimraf dist/*".
    // build an HTTP service locally
 "serve": "http-server -p 9090 dist/".  // open the browser  "open:dev": "opener http://localhost:9090".  // real-time refresh  "livereload": "live-reload --port 9091 dist/".  // build an HTML file  "build:html": "jade index.jade > dist/index.html".  // Re-execute the build as long as the CSS file has changed.  "watch:css": "watch 'npm run build:css' assets/styles/".  // Re-execute the build as long as the HTML file has changed  "watch:html": "watch 'npm run build:html' assets/html".  // Deploy to Amazon S3.  "deploy:prod": "s3-cli sync ./dist/ s3://example-com/prod-site/".  // build favicon  "build:favicon": "node scripts/favicon.js". Copy the code

11. Use NRM to manage NPM images

NRM (NPM Registry Manager) is the mirror source management tool of NPM. Sometimes foreign resources are too slow, so it can be used to quickly switch between NPM sources.

On the cli, run the following command to install NRM globally.

    npm install -g nrm
Copy the code

Run the NRM ls command to view the available sources.

Where, the one marked with * is the currently used source, and the output above indicates that the current source is Taobao source.

To switch to the CNPM source or another image, you can use the NRM use source name to switch:

    nrm use cnpm
Copy the code

You can add custom sources, especially for private sources within an enterprise, by executing the command NRM add < Registry >

, where reigstry is the source name and URL is the source path.

    nrm add registry http://registry.npm.frp.trmap.cn/
Copy the code

To delete the vm, run the following command:

    nrm del <registry> url
Copy the code

You can also use the NRM test to test the response time of the corresponding source to determine which image to use!

    nrm test taobao
Copy the code

If you feel the article is helpful to you, please help click a like 👍! Thank you very much!

🔗 Click here at 👉

This article is formatted using MDNICE