前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >npm script

npm script

作者头像
用户3258338
发布2019-07-19 17:14:02
3.1K0
发布2019-07-19 17:14:02
举报

学海无涯

哈喽,各位宝宝最近怎么样?你那里天气好吗?北京太热了,宝宝们要注意防暑哦,但还是要少喝冰豆浆。要好好照顾自己~

快速创建项目

npm script依赖package.json。npm 提供快速创建package.json的命令:npm init ,接下来会让你回答几个问题,你可以设置成自己想要设置的然后回车就行了。

然后就生成了pcakage.json文件。如果想要修改,可在文件中直接修改或者重新执行npm init。一路回车,之后package.json就是这样的。

{
  "name": "vue-test-1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

当然也有默认的快捷命令 npm init -y。生成的package.json和上面一样。我们可以设置一些默认值,当执行npm init 时就会取用默认值。

下面我们设置npm init的作者名为Lin

npm config set init.author.name "Lin"

之后执行npm init -y,生成的文件中author就有值了:

{
  "name": "vue-test-1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Lin",
  "license": "ISC"
}

还可以设置其他的默认值,与上面类似的:

npm config set init.author.email "XXX"
npm config set init.author.url "XXX"
npm config set init.license "XXX"
npm config set init.version "0.1"

执行任意命令

在刚刚创建的package.json文件中有这么一行:

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

当我们在命令行执行:npm run test时会输出:

echo "Error: no test specified" && exit 1

没错的,这是因为在package.json里面就是这么配置的。

实际上npm run 其实就是npm run-script 的简写。也可以用命令 npm test,也是简写啦!

每次我们执行npm run XXX流程如下:

  1. 在package.json里读取script对象的所有配置
  2. 以npm run 后的第一个参数作为键,取得该键对应的值,以这个值作为要执行的命令。如果没有找到直接报错。

举个例子:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    "eslint-test": "eslint **.js",
  },

eslint是从哪引用的呢?能直接用吗?当然喽。因为在npm 在执行指定script之前会把node_modules/.bin文件加入到$PATH的前面,也就是说任何内含中可执行的npm的依赖都可以用直接引用,也就是不需要写成如下:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    "eslint-test": "./node_modules/.bin/eslint **.js",
  },

执行多命令

执行多命令-串行 &&

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    "eslint-test": "./node_modules/.bin/eslint **.js",
    'testEslint': "npm run test && npm run eslint-test"
  },

执行多命令-并行 &

"scripts": {
    "lint:test": "echo \"Error: no test specified\" && exit 1"
    "lint:js": "./node_modules/.bin/eslint **.js",
    'testEslint': "npm run lint:test & npm run lint:test"
  },

如果需要执行多个命令,有一个很好用的工具 npm run all :

npm i npm-run-all 
"scripts": {
    ...
    "lint:all": "npm-run-all lint:test lint:js"
}

还支持通配符:

"scripts": {
    ...
    "lint:all": "npm-run-all lint:*"
}

上面是串行的写法,并行的写法:

"scripts": {
    ...,
    "lint:all": "npm-run-all --parallel lint:*"
}

愿我们有能力不向生活缴械投降---Lin

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 女程序员的日常 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档