二、npm scripts

一、执行原理

安装npm 包,会将其package.json bin 字段添加到node_modules bin 里面,创建对应的.cmd文件,因此:

例如:

"scripts":{
    "test": "mocha"
}
npm run test => 等同于
./node_modules/.bin/mocha
然后:
依旧是通过node 调用包bin字段对应的文件
bin 文件第一行
#!/usr/bin/env node

二、传入参数
"scripts":{
    "test": "mocha --reporter spec"
}
在 shell 中传入的参数都要使用 -- 隔开,这个 -- 被视作 npm run 命令参数的结束,-- 后面的内容都会原封不动地传给运行的命令。

三、通配符
"lint": "jshint *.js"
"lint": "jshint **/*.js"
*表示任意文件名,**表示任意一层子目录。
四、执行顺序
1.并行
$ npm run script1.js & npm run script2.js

继发执行(即只有前一个任务成功,才执行下一个任务
$ npm run script1.js && npm run script2.js
五、变量
npm 脚本有一个非常强大的功能,就是可以使用 npm 的内部变量。
{
  "name": "foo", 
  "version": "1.2.5",
  "scripts": {
    "view": "node view.js"
  }
}
// view.js
console.log(process.env.npm_package_name); // foo
console.log(process.env.npm_package_version); // 1.2.5
六、常用脚本
// 删除目录
"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",
 

参考:

npm scripts 使用指南

为什么使用 npm Scripts 构建项目

npm script 用法详解

 

posted @ 2018-11-28 19:52  shangyueyue  阅读(190)  评论(0编辑  收藏  举报