学海无涯
哈喽,各位宝宝最近怎么样?你那里天气好吗?北京太热了,宝宝们要注意防暑哦,但还是要少喝冰豆浆。要好好照顾自己~
快速创建项目
—
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流程如下:
举个例子:
"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