Node.js npm 包管理
npm 是 Node.js 的默认包管理器,用于安装、管理和发布 JavaScript 包。
npm 基础命令
Bash
# 查看版本
npm -v
# 初始化项目
npm init
npm init -y # 快速初始化
# 安装包
npm install express
npm i express # 简写
# 安装指定版本
npm install express@4.18.0
# 安装开发依赖
npm install jest --save-dev
npm i jest -D
# 全局安装
npm install nodemon -g
# 卸载包
npm uninstall express
npm remove express
# 更新包
npm update express
package.json
JSON
{
"name": "my-project",
"version": "1.0.0",
"description": "项目描述",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest"
},
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"jest": "^29.0.0",
"nodemon": "^3.0.0"
},
"keywords": ["node", "express"],
"author": "作者",
"license": "MIT"
}
依赖类型
| 类型 | 字段 | 说明 |
|---|---|---|
| 生产依赖 | dependencies | 运行时必需 |
| 开发依赖 | devDependencies | 开发时使用 |
| 可选依赖 | optionalDependencies | 可选安装 |
| 同伴依赖 | peerDependencies | 需宿主安装 |
Bash
# 生产依赖
npm i express
# 开发依赖
npm i jest -D
# 可选依赖
npm i package -O
版本号规则
版本号格式:主版本.次版本.补丁版本
Bash
# ^4.18.0:兼容次版本更新(4.18.x, 4.19.x, 不升到 5.x)
npm i express
# ~4.18.0:兼容补丁版本(4.18.x, 不升到 4.19)
npm i express --save-exact
# 4.18.0:精确版本
npm i express@4.18.0
# >=4.18.0:大于等于
npm i express@">=4.18.0"
# 最新版本
npm i express@latest
# 下一个版本
npm i express@next
npm scripts
JSON
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"build": "webpack --mode production",
"test": "jest",
"lint": "eslint src/",
"clean": "rm -rf dist/"
}
}
Bash
# 运行脚本
npm run start
npm start # start 可省略 run
npm run dev
npm run build
npm run test
npm test # test 可省略 run
package-lock.json
Bash
# 锁定依赖版本
# 自动生成,确保所有环境依赖一致
# 不要手动修改 package-lock.json
# 重新生成
npm install
全局包管理
Bash
# 全局安装位置
npm root -g
# 查看全局包
npm list -g
npm list -g --depth=0
# 常用全局包
npm i -g nodemon # 开发服务器
npm i -g n # Node 版本管理
npm i -g pm2 # 进程管理
npm i -g eslint # 代码检查
查看包信息
Bash
# 查看包信息
npm view express
# 查看版本
npm view express versions
# 查看最新版本
npm view express version
# 查看已安装版本
npm list express
# 查看包依赖
npm view express dependencies
发布包
Bash
# 注册 npm 用户
npm adduser
# 登录
npm login
# 发布
npm publish
# 发布到私有源
npm publish --registry=https://registry.my-company.com
# 更新版本后重新发布
npm version patch # 1.0.0 -> 1.0.1
npm version minor # 1.0.0 -> 1.1.0
npm version major # 1.0.0 -> 2.0.0
npm publish
清理缓存
Bash
# 清除缓存
npm cache clean --force
# 查看缓存
npm cache ls
# 验证缓存
npm cache verify
npm 镜像源
Bash
# 查看当前源
npm config get registry
# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com
# 使用 nrm 管理
npm i -g nrm
nrm ls
nrm use taobao
nrm use npm
要点总结
- npm init 初始化项目,生成 package.json
- npm install 安装依赖,-D 安装开发依赖
- package.json 定义项目配置和依赖
- package-lock.json 锁定依赖版本
- npm scripts 定义常用命令
- ^ 兼容次版本,~ 兼容补丁版本,精确版本无符号
📝 发现内容有误?点击此处直接编辑