你要知道的 Npm Script 都在这里

在拿到一个项目之后,如何看入口文件,如何运行项目,我们都会找到 package.json 中的 script 。
甚至在做项目做久之后,我们会自己写一些脚本来给开发提效,但你知道 NPM 脚本能做什么吗? 你知道如何传递一个参数给脚本? 你知道如何执行某个脚本文件么?
在这篇文章中,我将分享我如何充分利用 NPM 脚本。


## 介绍
NPM 脚本是 package.json 中定义的一组内置脚本和自定义脚本。他们的目标是提供一种简单的方法来执行重复的任务,比如:
- 启动项目
- 打包项目
- 执行单元测试,生成测试报告之类
- ……

那如何定义一个NPM脚本?需要做的就是设置它的名称,并在 package.json 文件的 script 属性中编写该脚本, 如下:

```javascript
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
}
```

**值得注意的是,NPM 中所有依赖的 node_modules bin 都可以在脚本中直接访问,就像在路径中被引用的一样**。比如: 


```
{
    "scripts": {
        "lint": "./node_modules/.bin/eslint .",
    }
}
// 此写法与上面效果相同
{
    "scripts": {
        "lint": "eslint ."
    }
}
```

## 命令
现在我们可以在终端中执行 npm run test 执行对应的 script 脚本, 如下: 
```javascript
➜  xxx npm run test

> xx@1.0.0 test /Users/beidan/Desktop/xxx
> echo "Error: no test specified" && exit 1

Error: no test specified
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! xx@1.0.0 test: `echo "Error: no test specified" && exit 1`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the xx@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/beidan/.npm/_logs/2021-02-19T06_40_42_472Z-debug.log
```
如果直接在终端中执行 npm test, 也是可以得到一样的结果 
```javascript
➜  xxx npm test

> xx@1.0.0 test /Users/beidan/Desktop/xxx
> ec

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值