Node.js npm 包管理器使用
npm 随 Node.js 自动安装,用于管理项目依赖和发布包。
npm 基础
Bash
# npm 随 Node.js 安装,检查版本
npm -v
# 10.x.x
# npm 帮助
npm help
npm help install
初始化项目
Bash
# 创建 package.json
npm init
# 快速初始化(跳过问答)
npm init -y
生成的 package.json:
JSON
{
"name": "my-project",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test\""
},
"keywords": [],
"author": "",
"license": "ISC"
}
安装依赖
Bash
# 安装包(写入 dependencies)
npm install express
npm i express # 简写
# 安装开发依赖(写入 devDependencies)
npm install jest --save-dev
npm i jest -D # 简写
# 安装指定版本
npm i express@4.18.0
# 安装最新版本
npm i express@latest
# 全局安装
npm i nodemon -g
package.json 依赖字段
JSON
{
"dependencies": {
"express": "^4.18.0", // 生产依赖
"mongoose": "^7.0.0"
},
"devDependencies": {
"jest": "^29.0.0", // 开发依赖
"nodemon": "^3.0.0"
}
}
| 依赖类型 | 命令 | 用途 |
|---|---|---|
| dependencies | npm i package | 运行时必需 |
| devDependencies | npm i package -D | 开发时使用 |
版本号规则
版本格式:主版本.次版本.补丁版本(如 4.18.0)
| 符号 | 含义 | 示例 |
|---|---|---|
| 无符号 | 精确版本 | 4.18.0 |
| ^ | 兼容次版本 | ^4.18.0 → 4.x.x |
| ~ | 兼容补丁版本 | ~4.18.0 → 4.18.x |
| > | 大于 | >4.18.0 |
| >= | 大于等于 | >=4.18.0 |
Bash
# 安装时使用不同版本规则
npm i express # ^4.18.0
npm i express@~4.18.0 # ~4.18.0
npm i express@4.18.0 # 精确版本
安装所有依赖
Bash
# 根据 package.json 安装所有依赖
npm install
# 只安装生产依赖
npm install --production
# 只安装开发依赖
npm install --only=dev
卸载与更新
Bash
# 卸载包
npm uninstall express
npm remove express # 简写
# 卸载开发依赖
npm uninstall jest -D
# 卸载全局包
npm uninstall nodemon -g
# 更新包
npm update express
# 更新所有包
npm update
npm scripts
JSON
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest",
"build": "webpack --mode production"
}
}
Bash
# 运行脚本
npm run start # 或 npm start
npm run dev
npm run test # 或 npm test
npm run build
查看包信息
Bash
# 查看包详情
npm view express
# 查看所有版本
npm view express versions
# 查看最新版本
npm view express version
# 查看已安装版本
npm list express
# 查看所有已安装包
npm list
npm list --depth=0 # 只显示顶层
package-lock.json
Bash
# 自动生成,锁定依赖版本
# 确保团队成员安装相同版本
# 删除 node_modules 后重新安装
rm -rf node_modules package-lock.json
npm install
不要手动修改 package-lock.json,由 npm 自动管理。
npm 镜像源
Bash
# 查看当前源
npm config get registry
# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com
# 恢复官方源
npm config set registry https://registry.npmjs.org
要点总结
- npm init 创建 package.json,-y 快速初始化
- npm install 安装依赖,-D 安装开发依赖
- ^ 兼容次版本更新,~ 兼容补丁版本更新
- npm scripts 定义常用命令
- package-lock.json 锁定依赖版本
- 可设置镜像源加速下载
📝 发现内容有误?点击此处直接编辑