npm script and package.json

1. What is the script npm

  When you create a project, such as node.js a vue project, or react a project, the project will generate a description file package.json.

For example npm allowed inside package.json file, field definitions using scripts script commands.

{
//...
"scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "e2e": "node test/e2e/runner.js",
    "test": "npm run e2e",
    "lint": "eslint --ext .js,.vue src test/e2e/specs",
    "build": "node build/build.js"
  },
}

  The above code fragment package.json a file, which is an object field of scripts. Each of its properties, corresponds to a script. For example, the build script command corresponds to a node build.js.

  Use npm run command at the command line, you can execute this script.

$ npm run build

  The equivalent to:

$ node build/build.js

  Similarly, in the above period of scripts, NPM RUN Test equivalent to NPM RUN E2E  , equivalent to node test / e2e / runner.js        

  These definitions package.json inside the script, the script called npm. Related script projects can be concentrated in one place; different projects script command, as long as the same function, you can have the same external interface. For example, users do not need to know how to test your project, just run npm run dev can

  View all current projects npm script commands can be used without any parameters  npm run  command.

$ npm run

 

2, npm principle

  Npm script principle is very simple. Whenever execution npm run, it will automatically create a shell script that executes the specified command in the shell script inside. Therefore, only if the shell (typically bash) that you can run, you can write a script npm inside.

  A special feature is, node_modules npm run this new shell, sets the current directory / .bin subdirectory in your PATH variable, after the execution, and then restored to their original PATH variable. Also it means that all scripts node_modules current directory / .bin subdirectories, you can directly call their feet, whose real name without having to add the path. For example, depending on the current project which has Mocha, just write directly mocha test it.

"test": "mocha test"

  Rather than written as follows.

"test": "./node_modules/.bin/mocha test"

  Since the only requirement is that npm script can be executed in the shell, so it is not necessarily Node script, any executable files can be written on the inside. npm script exit code, and keep the shell script rules. If the exit code is not 0, npm it considers the script execution failed.

 

3, wildcard

  Since npm script is a shell script, so you can use shell wildcards.

"lint": "jshint *.js"
"lint": "jshint **/*.js"

  The above code, * represents any file name, ** indicates any layer subdirectories. If you want to pass a wildcard original command, to prevent the escape shell, you want to escape the asterisk.

"test": "tap test/\*.js"

 

4, parameter passing

  Npm script to pass parameters to be used - mark.

"lint": "jshint **.js"

  The above npm run lint  pass parameters command, must be written as follows.

$ npm run lint --  --reporter checkstyle > checkstyle.xml

  Which may be further packaged package.json a command.

"lint": "jshint **.js",
"lint:checkstyle": "npm run lint -- --reporter checkstyle > checkstyle.xml"

 

5, the order of execution

  If npm script which need to perform multiple tasks, you need to clear their execution order. If performed in parallel (i.e., simultaneous parallel execution), ampersand can be used.

$ npm run script1.js & npm run script2.js

  If it is secondary to the implementation of (a task that is only the first successful, in order to perform the next task), you can use the && symbol.

$ npm run script1.js && npm run script2.js

 

6, the default value

  In general, npm script provided by the user. However, npm two script provides a default value. That is to say, without defining these two scripts, it can be used directly.

"start": "node server.js""install": "node-gyp rebuild"

  The above code, the default value npm run start is the node server.js, provided there is server.js this script in the project root directory; the default value npm run install a node-gyp rebuild, provided there is a binding project root directory. gyp file.

 

7, the hook

  It has pre script npm post two hooks. For example, the hook is prebuild build script commands 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"

  When the user performs npm run build is performed automatically in the following order.

npm run prebuild && npm run build && npm run postbuild

  Therefore, these two hooks inside, do some preparation and cleanup. Below is an example:

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

  npm default provides the following hooks:

prepublish,postpublish
preinstall,postinstall
preuninstall, postuninstall
preversion, postversion
pretest,posttest
crossing, poststop
prestart, record start
prerestart, postrestart

  Custom script commands can also add pre and post hook. For example, myscript this script commands, there premyscript and postmyscript hook. However, the pre and post double invalid, such as prepretest and postposttest is invalid.

  npm provide a npm_lifecycle_event variable returns the currently running script commands, such as pretest, test, posttest, and so on. So, you can use this variable, in which the same script file, write code for different npm scripts command. Consider 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!`);
}

  Note, prepublish this hook will not run before npm publish command, the command will be run before the npm install (without any parameters). This behavior makes it easy for users confused, so npm 4 introduces a new hook prepare, behavior is equivalent to prepublish, and, prepublish will only begin to run from the npm 5 before npm publish command.

 

8, shorthand

  There are four commonly used shorthand script npm.

  • npm start  is  npm run start  shorthand
  • npm stop  is  npm run stop  shorthand
  • npm test   is  npm run test   shorthand
  • npm  restart  npm  run  stop  &&  npm  run  restart  &&  npm  run  start 的简写

  npm start, npm stop, npm restart are better understood, and npm restart command is a complex, three actually execute script commands: stop, restart, start. Particular order of execution is as follows:

  1. prerestart
  2. crossing
  3. stop
  4. mail stop
  5. restart
  6. prestart
  7. start
  8. mail start
  9. postrestart

 

9, variable

  npm script has a very powerful feature is the ability to use the internal variables npm.

First, npm_package_ prefix, npm script can get package.json inside the field. For example, here is a package.json.

{
  "name": "foo", 
  "version": "1.2.5",
  "scripts": {
    "view": "node view.js"
  }
}

So, variable npm_package_name return foo, the variable npm_package_version return 1.2.5.

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

  In the above code, we process.env objects through the environment variable to get the field value package.json. If bash script can marry these two values ​​by $ npm_package_name and $ npm_package_version.

npm_package_ prefix also supports nested package.json field.

 "repository": {
    "type": "git",
    "url": "xxx"
  },
  scripts: {
    "view": "echo $npm_package_repository_type"
  }

  In the above code, attribute repository type fields, to be taken by npm_package_repository_type.

Here is another example:

"scripts": {
  "install": "foo.js"
}

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

  Then, npm script can also npm_config_ prefix, get npm configuration variables, namely npm config get xxx command value returned. For example, the current label issuing module to be taken through npm_config_tag.

"view": "echo $npm_config_tag",

  Note, package.json inside the config object that can be covered environment variable.

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

  The above code, npm_package_config_port variable returns 8080. This value may be covered by the following methods.

$ npm config set foo:port 80

  Finally, env command lists all environment variables.

"env": "env"

 

10, commonly used script examples

// delete the directory 
"Clean": "rimraf dist / *" ,

// local HTTP service to build a 
"serve": "HTTP-Server -p 9090 dist /" ,

// Open browser 
"Open: dev": "opener HTTP: // localhost: 9090" ,

// refreshed in real time 
 "livereload": "livereload --port 9091 dist /" ,

// 构建 HTML 文件
"build:html": "jade index.jade > dist/index.html",

// As long as there are changes in the CSS file, re-execute the construction of 
"Watch: CSS": "Watch 'npm RUN Build: CSS' Assets / Styles /" ,

// As long as there are changes in the HTML file, re-execute the construction of 
"Watch: HTML": "Watch 'npm RUN Build: HTML' Assets / HTML" ,

// 部署到 Amazon S3
"deploy:prod": "s3-cli sync ./dist/ s3://example-com/prod-site/",

// 构建 favicon
"build:favicon": "node scripts/favicon.js",

 

11, package.json Other Item Description

  For dependencies and devDependencies some explanation:

  When using npm install dependencies, if dependent --save installed inside dependencies module will be written to;

  The use --save-dev dependencies installed, it will be written inside devDependencies module to; if nothing to write, the default installation dependencies to go inside.

  For example, we use some of the build tools such as glup, webpack these only in the development environment was used in the package, only need to write to devDependencies can be.

  For targeting two environments, the configuration file by  process.env.NODE_ENV = 'development'  or   process.env.NODE_ENV = 'production'   to specify is the development or production environment.

 

12, package.json the bin properties

  package.json the bin is mapped command names and local files. If the installation is global, the file will be mapped to the global bin inside, after installation, to open a terminal anywhere in the file using the command line;

If it is installed locally, it will map the file to ./node_modules/.bin file folder inside the project, after installation, use the command line to execute the file in the project directory.

  for example:

  1. Create a new folder, open a terminal and enter the folder, the command   npm init -y  create a package.json file.
  2. Index.js then create a new file in the same directory package.json file, together with the test data. Note that the head index.js file must have the   #! / Usr / bin / env  node node.
  3. Increase in package.json bin property, set the mapping between the command name and index.js.
  4. Globally installed in the terminal the current directory: NPM the install -g   
  5. After the installation is successful, the folder can be opened in any terminal, package.json execution command set in the bin, it will perform a corresponding index.js code. As shown below

 

 

  At the same time, we open the global bin folder, you can find the global bin just add the following command tan-temp-bin 

  Like some of our common vue, vue-cli, create-react-app, etc. are by bin property commands mapped to the global

 

Reference links:

Ruan Yifeng --npm scripts Guide: http://www.ruanyifeng.com/blog/2016/10/npm_scripts.html

 

Guess you like

Origin www.cnblogs.com/tandaxia/p/12111226.html