Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

npm scripts #37

Open
AndreGeng opened this issue May 5, 2019 · 0 comments
Open

npm scripts #37

AndreGeng opened this issue May 5, 2019 · 0 comments

Comments

@AndreGeng
Copy link
Owner

AndreGeng commented May 5, 2019

  1. 传参
    向 npm 脚本传入参数,要使用--标明
npm run lint --  --reporter checkstyle > checkstyle.xml

也可以在package.json里面再封装一个命令。

"lint": "jshint **.js",
"lint:checkstyle": "npm run lint -- --reporter checkstyle > checkstyle.xml"
  1. 钩子
    npm 脚本有pre和post两个钩子。举例来说,build脚本命令的钩子就是prebuild和postbuild
  • prepublish,postpublish
  • preinstall,postinstall
  • preuninstall,postuninstall
  • preversion,postversion
  • pretest,posttest
  • prestop,poststop
  • prestart,poststart
  • prerestart,postrestart
    npm 提供一个npm_lifecycle_event变量,返回当前正在运行的脚本名称,比如pretest、test、posttest等等。所以,可以利用这个变量,在同一个脚本文件里面,为不同的npm scripts命令编写代码。请看下面的例子。
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!`);
}
  1. 变量
    npm 脚本有一个非常强大的功能,就是可以使用 npm 的内部变量。

首先,通过npm_package_前缀,npm 脚本可以拿到package.json里面的字段。例如,可以通过npm_package_repository_type取到package.json里repository.type的值
然后,npm 脚本还可以通过npm_config_前缀,拿到 npm 的配置变量,即npm config get xxx命令返回的值。比如,当前模块的发行标签,可以通过npm_config_tag取到。
注意,package.json里面的config对象,可以被环境变量覆盖。

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

上面代码中,npm_package_config_port变量返回的是8080。这个值可以用下面的方法覆盖。

npm config set foo:port 80

Reference:
npm scripts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant