Appearance
NPM
简介
NPM (Node Package Manager) 是 Node.js 的默认包管理器,也是世界上最大的软件注册表,包含超过 1.3 百万个包。它允许开发者安装、共享和管理项目依赖,是现代 JavaScript 开发的基础工具。
核心功能
包管理
bash
# 安装项目依赖
npm install
# 安装特定包
npm install lodash
# 安装开发依赖
npm install --save-dev jest
# 全局安装
npm install -g typescript版本控制
NPM 使用语义化版本控制(Semantic Versioning):
json
{
"dependencies": {
"express": "^4.17.1", // 兼容 4.17.1 及更高的 4.x 版本
"lodash": "~4.17.21", // 兼容 4.17.x 版本
"react": "16.13.1" // 精确匹配 16.13.1 版本
}
}脚本运行
json
{
"scripts": {
"start": "node server.js",
"test": "jest",
"build": "webpack --mode production"
}
}运行脚本:
bash
npm run start
npm test # 特殊脚本可以省略 run配置文件
package.json
项目的核心配置文件,定义了项目的元数据和依赖:
json
{
"name": "my-project",
"version": "1.0.0",
"description": "A sample project",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"jest": "^27.0.0"
},
"engines": {
"node": ">=14.0.0"
},
"author": "Your Name",
"license": "MIT"
}package-lock.json
自动生成的文件,确保团队成员和部署环境使用完全相同的依赖版本。
常用命令
bash
# 初始化新项目
npm init
npm init -y # 使用默认值
# 安装依赖
npm install # 安装所有依赖
npm install --production # 只安装生产依赖
# 更新依赖
npm update
npm update lodash # 更新特定包
# 卸载依赖
npm uninstall lodash
# 查看过时的依赖
npm outdated
# 运行安全审计
npm audit
npm audit fix # 自动修复问题
# 发布包
npm publishNPM 配置
.npmrc 文件
可以在项目或用户级别配置 NPM 行为:
# 设置私有仓库
registry=https://registry.npm.taobao.org/
# 设置作用域包的仓库
@mycompany:registry=https://npm.mycompany.com/
# 保存精确版本
save-exact=true最佳实践
依赖管理
- 使用
--save-exact锁定版本,避免意外更新 - 定期运行
npm audit检查安全漏洞 - 使用
.npmrc配置私有仓库和代理
脚本优化
- 创建复合脚本:
"dev": "npm run clean && npm run build -- --watch" - 使用
pre和post钩子:pretest,postinstall - 利用环境变量:
"build": "NODE_ENV=production webpack"
常见问题与解决方案
权限问题
bash
# 修复全局安装权限问题
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'缓存问题
bash
# 清除缓存
npm cache clean --force依赖冲突
bash
# 查看依赖树
npm ls
# 强制解析到特定版本
npm install lodash@4.17.21 --save-exact与其他包管理器对比
| 特性 | NPM | Yarn | PNPM |
|---|---|---|---|
| 安装速度 | 中等 | 较快 | 最快 |
| 磁盘空间使用 | 较高 | 较高 | 低 |
| 依赖解析 | 确定性 | 确定性 | 确定性 |
| 并行安装 | 支持 | 支持 | 支持 |
| 工作区支持 | 有限 | 良好 | 优秀 |
| 市场份额 | 最高 | 高 | 增长中 |