什么是 npm 脚本?
在package.json文件里面,使用scripts字段定义的脚本命令
如何执行是 npm 脚本?
不知道有什么 npm 脚本??
npm的原理??
每当执行npm run,就会自动新建一个 Shell,在这个 Shell 里面执行指定的脚本命令。
因此,只要是 Shell(一般是 Bash)可以运行的命令,就可以写在 npm 脚本里面。比较特别的是,npm run新建的这个 Shell,会将当前目录的node_modules/.bin子目录加入PATH变量,执行结束后,再将PATH变量恢复原样。这意味着,当前目录的node_modules/.bin子目录里面的所有脚本,都可以直接用脚本名调用,而不必加上路径。
由于 npm 脚本的唯一要求就是可以在 Shell 执行,因此它不一定是 Node 脚本,任何可执行文件都可以写在里面。npm 脚本的退出码,也遵守 Shell 脚本规则。如果退出码不是0,npm 就认为这个脚本执行失败。
通配符&转义
同shell
传参
向 npm 脚本传入参数,要使用--标明
一个命令执行多个任务??
默认脚本
不用定义,就可以直接使用(前提是项目根目录下有server.js脚本和rebuild文件)
钩子
npm 脚本有pre和post两个钩子
例子
自定义的脚本命令也可以加上pre和post钩子。比如,myscript这个脚本命令,也有premyscript和postmyscript钩子。不过,双重的pre和post无效,比如prepretest和postposttest是无效的。
默认的钩子
npm_lifecycle_event变量 (返回当前正在运行的脚本名称,pretest、test、posttest)
注意,prepublish这个钩子不仅会在npm publish命令之前运行,还会在npm install(不带任何参数)命令之前运行。这种行为很容易让用户感到困惑,所以 npm 4 引入了一个新的钩子prepare,行为等同于prepublish,而从 npm 5 开始,prepublish将只在npm publish命令之前运行。
简写
- npm start是npm run start的简写
- npm stop是npm run stop的简写
- npm test是npm run test的简写
- npm restart是npm run stop && npm run restart && npm run start的简写
执行顺序
1 prerestart
2 prestop
3 stop
4 poststop
5 restart
6 prestart
7 start
8 poststart
9 postrestart
npm 的内部变量
通过npm_package_前缀,npm 脚本可以拿到package.json里面的字段
(如果是 Bash 脚本,可以用$npm_package_前缀取值)
npm 脚本还可以通过npm_config_前缀,拿到 npm 的配置变量,即npm config get xxx命令返回的值。
比如,当前模块的发行标签,可以通过npm_config_tag取到。
注意 package.json里面的config对象,可以被环境变量覆盖。
列出所有环境变量
常用脚本示例
// 删除目录
"clean": "rimraf dist/*",
// 本地搭建一个 HTTP 服务
"serve": "http-server -p 9090 dist/",
// 打开浏览器
"open:dev": "opener http://localhost:9090",
// 实时刷新
"livereload": "live-reload --port 9091 dist/",
// 构建 HTML 文件
"build:html": "jade index.jade > dist/index.html",
// 只要 CSS 文件有变动,就重新执行构建
"watch:css": "watch 'npm run build:css' assets/styles/",
// 只要 HTML 文件有变动,就重新执行构建
"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",