目錄
什麼是 npm?
npm (Node Package Manager) 是 Node.js 的官方套件管理工具,也是世界上最大的軟體套件註冊中心。
核心功能
- 套件安裝:從 npm registry 安裝第三方套件
- 依賴管理:自動處理專案依賴關係
- 版本控制:管理套件版本和更新
- 腳本執行:執行專案自訂腳本
- 套件發布:發布自己的套件到 npm registry
主要特點
- ✅ 超過 200 萬個開源套件
- ✅ 自動處理依賴關係樹
- ✅ 語義化版本控制 (SemVer)
- ✅ 支援本地和全域安裝
- ✅ 內建腳本執行器
核心概念
package.json
專案的配置檔案,記錄:
- 專案資訊(名稱、版本、描述)
- 依賴套件清單
- 執行腳本
- 專案設定
node_modules
存放所有已安裝套件的目錄,包含:
- 專案依賴
- 依賴的依賴(遞迴)
- 套件的 node_modules
package-lock.json
鎖定檔案,記錄:
- 精確的套件版本
- 完整的依賴樹
- 套件的來源和雜湊值
- 確保團隊安裝相同版本
npm Registry
- 線上套件倉庫:https://registry.npmjs.org/
- 可設定私有 registry
- 支援企業內部 registry
快速開始
安裝 npm
npm 會隨 Node.js 一起安裝:
# 檢查是否已安裝
node -v
npm -v
# 更新 npm 到最新版本
npm install -g npm@latest
初始化專案
# 互動式建立 package.json
npm init
# 快速建立(使用預設值)
npm init -y
# 使用特定範本
npm init react-app my-app
第一個專案
# 建立專案目錄
mkdir my-project
cd my-project
# 初始化專案
npm init -y
# 安裝第一個套件
npm install express
# 檢視已安裝套件
npm list --depth=0
套件管理
安裝套件
# 安裝並加入 dependencies
npm install <package-name>
npm install express
npm i express # 簡寫
# 安裝多個套件
npm install express mongoose dotenv
# 安裝特定版本
npm install express@4.18.0
# 安裝開發依賴 (devDependencies)
npm install --save-dev jest
npm install -D eslint # 簡寫
# 全域安裝
npm install -g nodemon
npm install --global typescript
移除套件
# 移除套件
npm uninstall <package-name>
npm uninstall express
# 移除開發依賴
npm uninstall -D jest
# 移除全域套件
npm uninstall -g nodemon
更新套件
# 檢查可更新的套件
npm outdated
# 更新所有套件到最新版本(遵守 package.json 規則)
npm update
# 更新特定套件
npm update express
# 更新到最新版本(忽略 SemVer)
npm install express@latest
# 更新 npm 自身
npm install -g npm@latest
查看套件資訊
# 檢視套件詳細資訊
npm view <package-name>
npm info express
# 檢視套件所有版本
npm view express versions
# 檢視套件文檔
npm docs express
# 檢視套件 GitHub
npm repo express
# 列出已安裝套件
npm list
npm ls --depth=0 # 只顯示第一層
npm ls -g --depth=0 # 全域套件
package.json 配置
基本結構
{
"name": "my-project",
"version": "1.0.0",
"description": "專案描述",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest"
},
"keywords": ["javascript", "node"],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"nodemon": "^3.0.0"
}
}
重要欄位說明
| 欄位 | 說明 | 必填 |
|---|---|---|
name |
套件名稱(小寫、無空格) | ✅ |
version |
版本號(SemVer 格式) | ✅ |
description |
套件描述 | ❌ |
main |
入口檔案 | ❌ |
scripts |
腳本指令 | ❌ |
dependencies |
生產環境依賴 | ❌ |
devDependencies |
開發環境依賴 | ❌ |
engines |
指定 Node.js 版本 | ❌ |
repository |
原始碼倉庫 | ❌ |
dependencies vs devDependencies
{
"dependencies": {
// 生產環境需要的套件
"express": "^4.18.0",
"mongoose": "^7.0.0",
"dotenv": "^16.0.0"
},
"devDependencies": {
// 只在開發時需要的套件
"nodemon": "^3.0.0",
"jest": "^29.0.0",
"eslint": "^8.0.0"
}
}
指定 Node.js 版本
{
"engines": {
"node": ">=18.0.0",
"npm": ">=9.0.0"
}
}
常用指令
專案管理
# 安裝所有依賴(根據 package.json)
npm install
npm i
# 只安裝生產環境依賴
npm install --production
npm install --omit=dev
# 清理快取
npm cache clean --force
# 重新安裝所有套件
rm -rf node_modules package-lock.json
npm install
套件搜尋
# 在 npm registry 搜尋套件
npm search <keyword>
npm search express
# 搜尋並限制結果數量
npm search react --searchlimit=10
套件驗證
# 檢查套件安全漏洞
npm audit
# 自動修復漏洞
npm audit fix
# 強制修復(可能有破壞性更新)
npm audit fix --force
# 檢查套件完整性
npm ci # 使用 package-lock.json 進行乾淨安裝
專案清理
# 找出未使用的套件
npm prune
# 清理開發依賴
npm prune --production
# 找出重複的套件
npm dedupe
版本管理
語義化版本 (SemVer)
格式:主版本.次版本.修訂號 (MAJOR.MINOR.PATCH)
1.2.3
│ │ └─ 修訂號 (PATCH):向後相容的錯誤修復
│ └─── 次版本 (MINOR):向後相容的新功能
└───── 主版本 (MAJOR):不相容的 API 變更
版本符號
| 符號 | 說明 | 範例 | 匹配版本 |
|---|---|---|---|
^ |
相容更新(預設) | ^1.2.3 |
>=1.2.3 <2.0.0 |
~ |
次要更新 | ~1.2.3 |
>=1.2.3 <1.3.0 |
* |
任意版本 | * |
最新版本 |
> |
大於 | >1.2.3 |
>1.2.3 |
>= |
大於等於 | >=1.2.3 |
>=1.2.3 |
< |
小於 | <1.2.3 |
<1.2.3 |
<= |
小於等於 | <=1.2.3 |
<=1.2.3 |
- |
範圍 | 1.2.3 - 2.3.4 |
>=1.2.3 <=2.3.4 |
| 無符號 | 精確版本 | 1.2.3 |
1.2.3 |
版本範例
{
"dependencies": {
"express": "^4.18.0", // 4.18.0 <= version < 5.0.0
"mongoose": "~7.0.0", // 7.0.0 <= version < 7.1.0
"lodash": "4.17.21", // 精確版本 4.17.21
"axios": "*", // 最新版本
"dotenv": ">=16.0.0" // 16.0.0 或更高
}
}
更新版本號
# 手動編輯 package.json
vim package.json
# 使用 npm version 指令
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 version 2.0.0
腳本執行
定義腳本
在 package.json 中定義:
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest",
"build": "webpack --mode production",
"lint": "eslint .",
"format": "prettier --write ."
}
}
執行腳本
# 執行 npm 腳本
npm run <script-name>
npm run dev
npm run build
# 特殊腳本(可省略 run)
npm start # npm run start
npm test # npm run test
npm stop # npm run stop
npm restart # npm run restart
傳遞參數
# 使用 -- 傳遞參數
npm run test -- --watch
npm run build -- --mode=production
# 在腳本中使用
{
"scripts": {
"serve": "node index.js"
}
}
npm run serve -- --port=3000
# 等同於: node index.js --port=3000
生命週期腳本
npm 自動執行的腳本:
{
"scripts": {
"preinstall": "echo 安裝前執行",
"install": "echo 安裝時執行",
"postinstall": "echo 安裝後執行",
"prestart": "echo 啟動前執行",
"start": "node index.js",
"poststart": "echo 啟動後執行",
"pretest": "echo 測試前執行",
"test": "jest",
"posttest": "echo 測試後執行"
}
}
串聯腳本
{
"scripts": {
// 循序執行(使用 &&)
"build": "npm run clean && npm run compile",
// 平行執行(使用 &)
"dev": "npm run server & npm run client",
// 使用 npm-run-all 套件
"build:all": "npm-run-all clean compile minify",
"dev:all": "npm-run-all --parallel server client"
}
}
實戰範例
範例 1:建立 Express 專案
# 1. 建立專案目錄
mkdir my-express-app
cd my-express-app
# 2. 初始化專案
npm init -y
# 3. 安裝依賴
npm install express dotenv
npm install -D nodemon
# 4. 建立專案結構
mkdir src
touch src/index.js .env
# 5. 設定 package.json
cat > package.json << 'EOF'
{
"name": "my-express-app",
"version": "1.0.0",
"description": "Express API server",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": "^4.18.0",
"dotenv": "^16.0.0"
},
"devDependencies": {
"nodemon": "^3.0.0"
}
}
EOF
# 6. 啟動開發伺服器
npm run dev
範例 2:安全性檢查工作流程
# 檢查漏洞
npm audit
# 檢視詳細資訊
npm audit --json
# 自動修復(安全)
npm audit fix
# 查看會被修復的內容(不實際執行)
npm audit fix --dry-run
# 強制修復(可能有破壞性)
npm audit fix --force
# 只更新生產環境依賴
npm audit fix --only=prod
範例 3:多環境配置
{
"scripts": {
"start": "node src/index.js",
"dev": "NODE_ENV=development nodemon src/index.js",
"prod": "NODE_ENV=production node src/index.js",
"test": "NODE_ENV=test jest",
"build:dev": "webpack --mode development",
"build:prod": "webpack --mode production"
}
}
範例 4:使用私有 Registry
# 設定私有 registry
npm config set registry https://registry.company.com
# 或建立 .npmrc 檔案
echo "registry=https://registry.company.com" > .npmrc
# 為特定 scope 設定 registry
npm config set @mycompany:registry https://npm.company.com
# 切回官方 registry
npm config set registry https://registry.npmjs.org
最佳實踐
1. 使用 package-lock.json
# ✅ 提交 package-lock.json 到版本控制
git add package-lock.json
# ✅ 使用 npm ci 在 CI/CD 中安裝
npm ci # 比 npm install 更快、更可靠
# ❌ 不要忽略 package-lock.json
# .gitignore
# package-lock.json ← 移除這行
2. 區分生產和開發依賴
# ✅ 正確分類依賴
npm install express mongoose # 生產環境
npm install -D jest eslint nodemon # 開發環境
# ✅ 部署時只安裝生產依賴
npm install --production
3. 定期更新依賴
# 每週或每月執行
npm outdated # 檢查可更新套件
npm update # 更新套件
npm audit # 檢查安全漏洞
npm audit fix # 修復漏洞
4. 版本固定策略
{
"dependencies": {
// ❌ 風險:可能安裝不同版本
"express": "*",
"mongoose": "latest",
// ⚠️ 謹慎:允許次要更新
"lodash": "^4.17.21",
// ✅ 推薦:允許修訂更新
"axios": "~1.6.0",
// ✅ 最安全:精確版本(但失去自動修復)
"dotenv": "16.3.1"
}
}
5. 使用 .npmrc 配置
# 專案根目錄建立 .npmrc
cat > .npmrc << 'EOF'
# 儲存精確版本
save-exact=true
# 使用 package-lock
package-lock=true
# 不自動儲存
save=false
# 進度條
progress=true
# registry 設定
registry=https://registry.npmjs.org
EOF
6. 腳本命名規範
{
"scripts": {
// 開發相關
"dev": "nodemon src/index.js",
"start": "node src/index.js",
// 建構相關
"build": "webpack --mode production",
"build:dev": "webpack --mode development",
"build:prod": "webpack --mode production",
// 測試相關
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
// 程式碼品質
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
// 清理
"clean": "rm -rf dist node_modules",
"reset": "npm run clean && npm install"
}
}
7. 安全性檢查清單
# ✅ 定期執行安全審計
npm audit
# ✅ 使用工具檢查依賴
npx npm-check-updates -u # 檢查更新
# ✅ 檢查套件評分
npx snyk test # 需要註冊 Snyk
# ✅ 避免安裝可疑套件
npm view <package-name> --json # 檢查套件資訊
常見問題
問題 1:npm install 很慢
原因:網路問題或 registry 伺服器慢
解決方案:
# 使用淘寶鏡像(中國地區)
npm config set registry https://registry.npmmirror.com
# 或使用 cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install
# 清理快取
npm cache clean --force
# 使用 npm ci(更快)
npm ci
問題 2:EACCES 權限錯誤
錯誤訊息:Error: EACCES: permission denied
解決方案:
# 方法 1:修改 npm 全域目錄權限(推薦)
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
# 方法 2:使用 npx(不需全域安裝)
npx <package-name>
# 方法 3:修復權限(macOS/Linux)
sudo chown -R $(whoami) ~/.npm
sudo chown -R $(whoami) /usr/local/lib/node_modules
問題 3:package-lock.json 衝突
情境:Git merge 時 package-lock.json 產生衝突
解決方案:
# 方法 1:重新生成
rm package-lock.json
npm install
# 方法 2:使用 npm 修復
npm install --package-lock-only
# 方法 3:手動解決後驗證
npm install
npm audit
問題 4:依賴版本不相容
錯誤訊息:ERESOLVE unable to resolve dependency tree
解決方案:
# 方法 1:使用 --legacy-peer-deps
npm install --legacy-peer-deps
# 方法 2:使用 --force(不推薦)
npm install --force
# 方法 3:更新 npm 版本
npm install -g npm@latest
# 方法 4:檢查並調整版本
npm view <package-name> peerDependencies
問題 5:node_modules 太大
問題:node_modules 目錄佔用大量空間
解決方案:
# 找出大型套件
npx npkill # 互動式清理工具
# 或使用
du -sh node_modules/* | sort -hr | head -10
# 移除未使用的套件
npm prune
# 使用 pnpm 或 yarn(節省空間)
npm install -g pnpm
pnpm install # 使用符號連結,節省空間
問題 6:無法找到模組
錯誤訊息:Error: Cannot find module 'xxx'
解決方案:
# 1. 確認套件已安裝
npm list <package-name>
# 2. 重新安裝
npm install
# 3. 清理並重新安裝
rm -rf node_modules package-lock.json
npm install
# 4. 檢查 import 路徑是否正確
# ✅ const express = require('express');
# ❌ const express = require('Express'); // 注意大小寫
總結
核心要點
- npm 是 Node.js 生態系統的核心工具,管理套件依賴
- package.json 定義專案資訊和依賴,務必納入版本控制
- package-lock.json 鎖定精確版本,確保團隊一致性
- 語義化版本 使用 SemVer 規範管理套件版本
- 安全性 定期執行
npm audit檢查漏洞
必記指令
| 指令 | 說明 |
|---|---|
npm init -y |
快速初始化專案 |
npm install <pkg> |
安裝套件 |
npm install -D <pkg> |
安裝開發依賴 |
npm uninstall <pkg> |
移除套件 |
npm update |
更新套件 |
npm outdated |
檢查可更新套件 |
npm audit |
安全檢查 |
npm audit fix |
自動修復漏洞 |
npm run <script> |
執行腳本 |
npm ci |
CI/CD 乾淨安裝 |
最佳實踐摘要
- ✅ 使用
package-lock.json並納入版本控制 - ✅ 區分
dependencies和devDependencies - ✅ 定期執行
npm audit和npm update - ✅ 在 CI/CD 使用
npm ci而非npm install - ✅ 使用語義化版本管理依賴
- ✅ 設定
.npmrc統一團隊配置 - ✅ 謹慎使用
^和~版本符號 - ✅ 建立清晰的 npm scripts 命名規範
延伸學習
- pnpm:更快、更節省空間的套件管理工具
- yarn:Facebook 開發的替代方案
- npx:直接執行套件,無需全域安裝
- monorepo:使用 npm workspaces 管理多套件專案
- 私有 registry:建立企業內部套件倉庫
建立日期:2025-11-19 最後更新:2025-11-19