目錄
- 簡介
- 安裝與配置
- 基礎命令
- 依賴管理
- 版本控制
- 腳本管理
- 包發布
- 高級命令
- 配置管理
- 最佳實踐
- 常見問題
1. 簡介
npm (Node Package Manager) 是 Node.js 的官方包管理工具,提供:
- 130萬+ 開源包的注冊表訪問
- 依賴解析與版本管理
- 項目腳本自動化
- 私有包管理能力
- 完整的包生命周期管理
2. 安裝與配置
2.1 安裝Node.js
# 通過官方安裝包
https://nodejs.org# 驗證安裝
node -v
npm -v
2.2 配置初始化
npm init # 交互式創建package.json
npm init -y # 快速生成默認配置
2.3 鏡像源配置
npm config set registry https://registry.npmmirror.com # 阿里云鏡像
npm config get registry # 查看當前源
npm config delete registry # 恢復默認源
3. 基礎命令
3.1 包安裝
npm install # 安裝所有依賴
npm install lodash # 安裝生產依賴
npm install eslint -D # 安裝開發依賴
npm install react@18.2.0 # 安裝指定版本
npm install ../my-package # 安裝本地包
3.2 包管理
npm uninstall axios # 卸載包
npm update # 更新所有依賴
npm outdated # 檢查過時依賴
npm ls # 查看依賴樹
npm cache clean --force # 清理緩存
4. 依賴管理
4.1 依賴類型
{"dependencies": { // 生產環境依賴"lodash": "^4.17.21"},"devDependencies": { // 開發環境依賴"webpack": "^5.75.0"},"peerDependencies": { // 宿主環境依賴"react": ">=16.8.0"},"optionalDependencies": { // 可選依賴"fsevents": "^2.3.2"}
}
4.2 全局安裝
npm install -g typescript # 全局安裝
npm list -g --depth=0 # 查看全局安裝包
5. 版本控制
5.1 語義化版本 (SemVer)
^1.2.3 # 兼容次要版本和補丁 (1.x.x)
~1.2.3 # 僅兼容補丁版本 (1.2.x)
1.2.x # 指定次要版本
* # 最新版本
5.2 版本鎖定
npm shrinkwrap # 生成npm-shrinkwrap.json
npm ci # 嚴格按lockfile安裝
6. 腳本管理
6.1 基礎腳本
{"scripts": {"start": "node index.js","test": "jest","build": "webpack --mode production","prepublish": "npm run build"}
}
6.2 高級用法
npm run test -- --coverage # 傳遞參數
npm run lint & npm run build # 并行執行
npm run prestart # 生命周期鉤子
7. 包發布
7.1 發布流程
npm login # 登錄賬號
npm publish # 發布公開包
npm publish --access public # 明確發布公開包
npm version patch # 版本號升級
npm deprecate <pkg>@<version> "message" # 標記棄用
7.2 私有包
npm init --scope=yourorg # 創建組織包
npm publish --access restricted # 發布私有包
8. 高級命令
8.1 審計與安全
npm audit # 安全審計
npm audit fix # 自動修復漏洞
npm fund # 查看依賴資金信息
8.2 調試工具
npm view react # 查看包信息
npm docs lodash # 打開文檔網站
npm repo webpack # 打開源碼倉庫
npm explore react -- npm ls # 進入包目錄
9. 配置管理
9.1 配置文件
.npmrc 優先級:
項目級 > 用戶級 > 全局 > npm內置
9.2 常用配置項
npm config set save-exact true # 精確版本
npm config set script-shell bash # 指定腳本shell
npm config set engine-strict true # 嚴格引擎檢查
10. 最佳實踐
- 使用
npm ci
代替npm install
在CI環境 - 定期執行
npm outdated
和npm update
- 提交
package-lock.json
到版本控制 - 使用
npm audit
進行安全審計 - 為CLI工具添加
bin
字段 - 使用
.npmignore
控制發布內容 - 合理使用
peerDependencies
避免重復依賴 - 對私有包使用作用域 (
@org/package
)
11. 常見問題
Q1: 安裝權限錯誤
# 解決方案:
sudo chown -R $(whoami) ~/.npm
# 或使用Node版本管理工具(nvm)
Q2: 依賴沖突解決
npm ls <package-name> # 查看依賴路徑
npm dedupe # 嘗試優化依賴樹
Q3: 加速安裝
npm install --prefer-offline # 優先使用緩存
npm config set prefer-offline true # 永久設置
轉載吱一聲~