package.json基本概念
package.json是用来识别项目并且处理项目的依赖关系的,package.json可以让npm启动项目、运行脚本、安装依赖项,一个项目里面必须要有package.json文件才能用npm安装依赖包。
可以用以下两个命令来生成package.json文件:
npm init -y
//或者
npm init //然后一直回车
详细的内容解析如下package.json详解
{
//name和version最重要,如果没有模块无法被安装
"name": "package.json", // 项目名称
"version": "1.0.0", // 项目版本(格式:大版本.次要版本.小版本)
"private":true,//是否是私有项目,一般公司的项目是私有的
"description": "", // 项目描述
"main": "index.js", // 入口文件
"scripts": { //指定运行脚本命令的 npm 命令行缩写
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [], //关键词,一个字符串数组,方便别人搜索
"author": "", //作者
"license": "ISC" //许可证
"bugs"://填写一个bug提交地址或者一个邮箱,被你的模块坑到的人可以通过这里吐槽
{ "url" : "https://github.com/owner/project/issues"
, "email" : "project@hostname.com"
},
"dependencies":{}//指定了项目运行所依赖的模块,在生产环境中要用到的,比如antd
"devDependencies":{}//指定了项目开发所需要的模块,开发环境要用的,项目运行的时候又用不到的,比如webpack和eslint
}
scripts属性
scripts对象package.json中的一个属性,它指定了项目的生命周期个各个环节需要执行的命令,供npm直接调用。key是生命周期中的事件,value是要执行的命令。
{
"scripts":{
"start":"nodemon index.ts",
}
}
//执行npm run start
//相当于执行 nodemon index.ts
运行单个命令
{
"scripts":{
"lint":"node hello.js",
"test":"node test.js"
}
}
npm run-script lint相当于npm run lint,就会执行node hello.js;npm run-script test相当于npm run test,就会执行node test.js;npm run是npm run-script的缩写;
运行多个命令
串行
用 && 符号把多条 npm script 按先后顺序串起来即可
"scripts": {
"frotend": "echo \"前端服务启动啦\"",
"server": "echo \"后端服务启动啦\"",
"all": "npm run frotend && npm run server",
},
命令行输入:npm run all
注意:串行执行的时候如果前序命令失败,后续全部命令都会终止。
并行
为了提高效率,用 & 符号把多条 npm script 按先后顺序串起来即可实现多个命令并行执行
"scripts": {
"all": "npm run frotend & npm run server",
},
运行npm run 命令之后会干啥
// package.json
"name": "angular-cli-xxxx-project",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "node ./src/index.js",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
}
当我们运行npm run build命令的时候,就会去scripts字段里找到build对应的ng build命令。虽然ng没有全局安装,但是npm会到./node_modules/.bin目录里找到ng.js文件作为node脚本来执行,也就是相当于执行了./node_modules/.bin/ng build命令(build作为参数传入)。
为什么不能直接执行ng build命令呢?
因为操作系统里只有npm相关的命令,不存在ng build这条命令,执行结果会报错。