npm-helper
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNPM Package Management Assistant Skill
NPM包管理助手技能
NPM and Node.js package management, project configuration, and dependency troubleshooting.
NPM与Node.js包管理、项目配置及依赖问题排查。
Instructions
使用说明
You are a Node.js and NPM ecosystem expert. When invoked:
-
Package Management:
- Install and manage npm packages
- Handle package.json configuration
- Manage lock files (package-lock.json)
- Use npm, yarn, or pnpm effectively
- Configure workspaces and monorepos
-
Project Setup:
- Initialize new Node.js projects
- Configure scripts and lifecycle hooks
- Set up project structure
- Configure development tools
- Manage multiple package managers
-
Dependency Management:
- Handle version ranges and semver
- Resolve dependency conflicts
- Audit for security vulnerabilities
- Update dependencies safely
- Manage peer dependencies
-
Troubleshooting:
- Fix module resolution errors
- Resolve version conflicts
- Debug installation issues
- Clear cache and rebuild
- Handle platform-specific issues
-
Best Practices: Provide guidance on package management, versioning, security, and performance optimization
你是Node.js与NPM生态系统专家。被调用时:
-
包管理:
- 安装并管理npm包
- 处理package.json配置
- 管理锁文件(package-lock.json)
- 高效使用npm、yarn或pnpm
- 配置工作区与单仓库(monorepo)
-
项目初始化:
- 初始化新的Node.js项目
- 配置脚本与生命周期钩子
- 搭建项目结构
- 配置开发工具
- 管理多个包管理器
-
依赖管理:
- 处理版本范围与语义化版本(semver)
- 解决依赖冲突
- 审计安全漏洞
- 安全更新依赖
- 管理对等依赖
-
问题排查:
- 修复模块解析错误
- 解决版本冲突
- 调试安装问题
- 清理缓存并重建
- 处理平台特定问题
-
最佳实践: 提供包管理、版本控制、安全与性能优化相关指导
Package Manager Comparison
包管理器对比
npm (Default)
npm(默认)
bash
undefinedbash
undefinedPros: Default in Node.js, widely supported
优点:Node.js默认自带,支持广泛
Cons: Slower than alternatives
缺点:比其他工具慢
Initialize project
初始化项目
npm init
npm init -y # Skip prompts
npm init
npm init -y # 跳过交互提示
Install dependencies
安装依赖
npm install express
npm install --save-dev jest
npm install express
npm install --save-dev jest
Install all dependencies
安装所有依赖
npm install
npm install
Update dependencies
更新依赖
npm update
npm update express
npm update
npm update express
Remove package
移除包
npm uninstall express
npm uninstall express
Run scripts
运行脚本
npm run build
npm test # Shorthand for npm run test
npm start # Shorthand for npm run start
npm run build
npm test # npm run test的简写
npm start # npm run start的简写
List installed packages
列出已安装包
npm list
npm list --depth=0 # Only top-level
npm list
npm list --depth=0 # 仅显示顶层包
Check for outdated packages
检查过时包
npm outdated
undefinednpm outdated
undefinedYarn (v1 Classic)
Yarn(v1 经典版)
bash
undefinedbash
undefinedPros: Faster, better UX, workspaces
优点:速度更快,用户体验更好,支持工作区
Cons: Extra tool to install
缺点:需要额外安装
Install Yarn
安装Yarn
npm install -g yarn
npm install -g yarn
Initialize project
初始化项目
yarn init
yarn init -y
yarn init
yarn init -y
Install dependencies
安装依赖
yarn add express
yarn add --dev jest
yarn add express
yarn add --dev jest
Install all dependencies
安装所有依赖
yarn install
yarn # Shorthand
yarn install
yarn # 简写
Update dependencies
更新依赖
yarn upgrade
yarn upgrade express
yarn upgrade
yarn upgrade express
Remove package
移除包
yarn remove express
yarn remove express
Run scripts
运行脚本
yarn build
yarn test
yarn start
yarn build
yarn test
yarn start
List installed packages
列出已安装包
yarn list
yarn list --depth=0
yarn list
yarn list --depth=0
Check for outdated packages
检查过时包
yarn outdated
yarn outdated
Interactive upgrade
交互式更新
yarn upgrade-interactive
undefinedyarn upgrade-interactive
undefinedpnpm (Fast & Efficient)
pnpm(快速高效)
bash
undefinedbash
undefinedPros: Fastest, disk space efficient, strict
优点:速度最快,磁盘空间利用率高,严格模式
Cons: Less common, some compatibility issues
缺点:使用范围较窄,存在部分兼容性问题
Install pnpm
安装pnpm
npm install -g pnpm
npm install -g pnpm
Initialize project
初始化项目
pnpm init
pnpm init
Install dependencies
安装依赖
pnpm add express
pnpm add -D jest
pnpm add express
pnpm add -D jest
Install all dependencies
安装所有依赖
pnpm install
pnpm install
Update dependencies
更新依赖
pnpm update
pnpm update express
pnpm update
pnpm update express
Remove package
移除包
pnpm remove express
pnpm remove express
Run scripts
运行脚本
pnpm build
pnpm test
pnpm start
pnpm build
pnpm test
pnpm start
List installed packages
列出已安装包
pnpm list
pnpm list --depth=0
pnpm list
pnpm list --depth=0
Check for outdated packages
检查过时包
pnpm outdated
undefinedpnpm outdated
undefinedYarn v3 (Berry)
Yarn v3(Berry)
bash
undefinedbash
undefinedPros: Zero-installs, Plug'n'Play, smaller size
优点:零安装,即插即用(Plug'n'Play),体积更小
Cons: Different from v1, migration needed
缺点:与v1差异大,需要迁移
Enable Yarn Berry
启用Yarn Berry
yarn set version berry
yarn set version berry
Install dependencies
安装依赖
yarn add express
yarn add -D jest
yarn add express
yarn add -D jest
Use Plug'n'Play (default in v3)
使用即插即用(v3默认)
No node_modules folder
无node_modules文件夹
Or use node_modules
或使用node_modules
echo "nodeLinker: node-modules" >> .yarnrc.yml
echo "nodeLinker: node-modules" >> .yarnrc.yml
Zero-installs (commit .yarn/cache)
零安装(提交.yarn/cache)
echo "enableGlobalCache: false" >> .yarnrc.yml
undefinedecho "enableGlobalCache: false" >> .yarnrc.yml
undefinedUsage Examples
使用示例
@npm-helper
@npm-helper --init-project
@npm-helper --fix-dependencies
@npm-helper --audit-security
@npm-helper --migrate-to-pnpm
@npm-helper --troubleshoot@npm-helper
@npm-helper --init-project
@npm-helper --fix-dependencies
@npm-helper --audit-security
@npm-helper --migrate-to-pnpm
@npm-helper --troubleshootProject Initialization
项目初始化
Basic Project Setup
基础项目搭建
bash
undefinedbash
undefinedInitialize package.json
初始化package.json
npm init -y
npm init -y
Install common dependencies
安装常用依赖
npm install express dotenv
npm install express dotenv
Install dev dependencies
安装开发依赖
npm install --save-dev
nodemon
eslint
prettier
jest
@types/node
typescript
nodemon
eslint
prettier
jest
@types/node
typescript
npm install --save-dev
nodemon
eslint
prettier
jest
@types/node
typescript
nodemon
eslint
prettier
jest
@types/node
typescript
Create basic structure
创建基础目录结构
mkdir -p src tests
touch src/index.js tests/index.test.js
mkdir -p src tests
touch src/index.js tests/index.test.js
Create .gitignore
创建.gitignore
cat > .gitignore << EOF
node_modules/
.env
.env.local
dist/
build/
coverage/
.DS_Store
*.log
EOF
cat > .gitignore << EOF
node_modules/
.env
.env.local
dist/
build/
coverage/
.DS_Store
*.log
EOF
Create .nvmrc for Node version
创建.nvmrc指定Node版本
node -v > .nvmrc
undefinednode -v > .nvmrc
undefinedTypeScript Project Setup
TypeScript项目搭建
bash
undefinedbash
undefinedInitialize project
初始化项目
npm init -y
npm init -y
Install TypeScript and types
安装TypeScript及类型定义
npm install --save-dev
typescript
@types/node
@types/express
ts-node
nodemon
typescript
@types/node
@types/express
ts-node
nodemon
npm install --save-dev
typescript
@types/node
@types/express
ts-node
nodemon
typescript
@types/node
@types/express
ts-node
nodemon
Initialize TypeScript
初始化TypeScript
npx tsc --init
npx tsc --init
Configure tsconfig.json
配置tsconfig.json
cat > tsconfig.json << EOF
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
EOF
cat > tsconfig.json << EOF
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
EOF
Update package.json scripts
更新package.json脚本
npm pkg set scripts.build="tsc"
npm pkg set scripts.dev="nodemon src/index.ts"
npm pkg set scripts.start="node dist/index.js"
undefinednpm pkg set scripts.build="tsc"
npm pkg set scripts.dev="nodemon src/index.ts"
npm pkg set scripts.start="node dist/index.js"
undefinedModern ESM Project Setup
现代ESM项目搭建
json
{
"name": "my-esm-project",
"version": "1.0.0",
"type": "module",
"main": "dist/index.js",
"scripts": {
"dev": "node --watch src/index.js",
"build": "tsc",
"start": "node dist/index.js",
"test": "node --test"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"@types/node": "^20.10.0",
"typescript": "^5.3.0"
}
}json
{
"name": "my-esm-project",
"version": "1.0.0",
"type": "module",
"main": "dist/index.js",
"scripts": {
"dev": "node --watch src/index.js",
"build": "tsc",
"start": "node dist/index.js",
"test": "node --test"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"@types/node": "^20.10.0",
"typescript": "^5.3.0"
}
}package.json Configuration
package.json配置
Essential Fields
核心字段
json
{
"name": "my-package",
"version": "1.0.0",
"description": "A helpful package",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"engines": {
"node": ">=18.0.0",
"npm": ">=9.0.0"
},
"scripts": {
"dev": "nodemon src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint src/**/*.ts --fix",
"format": "prettier --write \"src/**/*.ts\"",
"typecheck": "tsc --noEmit",
"prepare": "husky install",
"prepublishOnly": "npm run build && npm test"
},
"keywords": ["node", "javascript", "helper"],
"author": "Your Name <email@example.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/user/repo.git"
},
"bugs": {
"url": "https://github.com/user/repo/issues"
},
"homepage": "https://github.com/user/repo#readme"
}json
{
"name": "my-package",
"version": "1.0.0",
"description": "实用工具包",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"engines": {
"node": ">=18.0.0",
"npm": ">=9.0.0"
},
"scripts": {
"dev": "nodemon src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint src/**/*.ts --fix",
"format": "prettier --write \"src/**/*.ts\"",
"typecheck": "tsc --noEmit",
"prepare": "husky install",
"prepublishOnly": "npm run build && npm test"
},
"keywords": ["node", "javascript", "helper"],
"author": "你的名字 <email@example.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/user/repo.git"
},
"bugs": {
"url": "https://github.com/user/repo/issues"
},
"homepage": "https://github.com/user/repo#readme"
}Dependency Types
依赖类型
json
{
"dependencies": {
"express": "^4.18.2",
"dotenv": "^16.3.1"
},
"devDependencies": {
"typescript": "^5.3.0",
"jest": "^29.7.0",
"eslint": "^8.55.0",
"prettier": "^3.1.0"
},
"peerDependencies": {
"react": ">=16.8.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
},
"optionalDependencies": {
"fsevents": "^2.3.3"
},
"bundledDependencies": [
"internal-package"
]
}json
{
"dependencies": {
"express": "^4.18.2",
"dotenv": "^16.3.1"
},
"devDependencies": {
"typescript": "^5.3.0",
"jest": "^29.7.0",
"eslint": "^8.55.0",
"prettier": "^3.1.0"
},
"peerDependencies": {
"react": ">=16.8.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
},
"optionalDependencies": {
"fsevents": "^2.3.3"
},
"bundledDependencies": [
"internal-package"
]
}Scripts Best Practices
脚本最佳实践
json
{
"scripts": {
"// Development": "",
"dev": "nodemon src/index.ts",
"dev:debug": "nodemon --inspect src/index.ts",
"// Building": "",
"build": "npm run clean && tsc",
"clean": "rm -rf dist",
"prebuild": "npm run lint",
"postbuild": "echo 'Build complete!'",
"// Testing": "",
"test": "jest",
"test:unit": "jest --testPathPattern=unit",
"test:integration": "jest --testPathPattern=integration",
"test:e2e": "jest --testPathPattern=e2e",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"// Linting & Formatting": "",
"lint": "eslint . --ext .ts,.js",
"lint:fix": "eslint . --ext .ts,.js --fix",
"format": "prettier --write \"src/**/*.{ts,js,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,js,json}\"",
"// Type Checking": "",
"typecheck": "tsc --noEmit",
"typecheck:watch": "tsc --noEmit --watch",
"// Combined": "",
"validate": "npm run lint && npm run typecheck && npm test",
"ci": "npm run validate && npm run build",
"// Release": "",
"prepare": "husky install",
"prepublishOnly": "npm run ci",
"version": "npm run build && git add -A dist",
"postversion": "git push && git push --tags"
}
}json
{
"scripts": {
"// 开发相关": "",
"dev": "nodemon src/index.ts",
"dev:debug": "nodemon --inspect src/index.ts",
"// 构建相关": "",
"build": "npm run clean && tsc",
"clean": "rm -rf dist",
"prebuild": "npm run lint",
"postbuild": "echo '构建完成!'",
"// 测试相关": "",
"test": "jest",
"test:unit": "jest --testPathPattern=unit",
"test:integration": "jest --testPathPattern=integration",
"test:e2e": "jest --testPathPattern=e2e",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"// 代码检查与格式化": "",
"lint": "eslint . --ext .ts,.js",
"lint:fix": "eslint . --ext .ts,.js --fix",
"format": "prettier --write \"src/**/*.{ts,js,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,js,json}\"",
"// 类型检查": "",
"typecheck": "tsc --noEmit",
"typecheck:watch": "tsc --noEmit --watch",
"// 组合命令": "",
"validate": "npm run lint && npm run typecheck && npm test",
"ci": "npm run validate && npm run build",
"// 发布相关": "",
"prepare": "husky install",
"prepublishOnly": "npm run ci",
"version": "npm run build && git add -A dist",
"postversion": "git push && git push --tags"
}
}Dependency Version Management
依赖版本管理
Semantic Versioning (semver)
语义化版本(semver)
json
{
"dependencies": {
"express": "4.18.2", // Exact version
"lodash": "^4.17.21", // Compatible (4.x.x, < 5.0.0)
"axios": "~1.6.0", // Approximately (1.6.x)
"react": ">=16.8.0", // At least
"vue": "<4.0.0", // Less than
"moment": "*", // Latest (not recommended)
"date-fns": "latest" // Latest (not recommended)
}
}json
{
"dependencies": {
"express": "4.18.2", // 精确版本
"lodash": "^4.17.21", // 兼容更新(4.x.x,<5.0.0)
"axios": "~1.6.0", // 补丁更新(1.6.x)
"react": ">=16.8.0", // 最低版本
"vue": "<4.0.0", // 低于指定版本
"moment": "*", // 最新版本(不推荐)
"date-fns": "latest" // 最新版本(不推荐)
}
}Version Range Examples
版本范围示例
bash
undefinedbash
undefinedCaret (^) - Compatible updates
脱字符(^)- 兼容更新
^1.2.3 # >=1.2.3 <2.0.0
^0.2.3 # >=0.2.3 <0.3.0
^0.0.3 # >=0.0.3 <0.0.4
^1.2.3 # >=1.2.3 <2.0.0
^0.2.3 # >=0.2.3 <0.3.0
^0.0.3 # >=0.0.3 <0.0.4
Tilde (~) - Patch updates only
波浪号(~)- 仅补丁更新
~1.2.3 # >=1.2.3 <1.3.0
~1.2 # >=1.2.0 <1.3.0
~1 # >=1.0.0 <2.0.0
~1.2.3 # >=1.2.3 <1.3.0
~1.2 # >=1.2.0 <1.3.0
~1 # >=1.0.0 <2.0.0
Advanced ranges
高级范围
1.2.3 - 2.3.4 # >=1.2.3 <=2.3.4
1.2.x # 1.2.0, 1.2.1, etc.
-
# Any version
undefined1.2.3 - 2.3.4 # >=1.2.3 <=2.3.4
1.2.x # 1.2.0, 1.2.1等
-
# 任意版本
undefinedLock File Management
锁文件管理
bash
undefinedbash
undefinednpm - package-lock.json
npm - package-lock.json
Always commit package-lock.json
务必提交package-lock.json到版本控制
npm ci # Install from lock file (CI/CD)
npm install # Updates lock file if needed
npm ci # 从锁文件安装(CI/CD环境)
npm install # 必要时更新锁文件
Yarn - yarn.lock
Yarn - yarn.lock
Always commit yarn.lock
务必提交yarn.lock到版本控制
yarn install --frozen-lockfile # Don't update lock file
yarn install --frozen-lockfile # 不更新锁文件
pnpm - pnpm-lock.yaml
pnpm - pnpm-lock.yaml
Always commit pnpm-lock.yaml
务必提交pnpm-lock.yaml到版本控制
pnpm install --frozen-lockfile # Don't update lock file
undefinedpnpm install --frozen-lockfile # 不更新锁文件
undefinedSecurity and Auditing
安全与审计
Vulnerability Scanning
漏洞扫描
bash
undefinedbash
undefinednpm audit
npm审计
npm audit
npm audit --json # JSON output
npm audit --audit-level=moderate # Only moderate+
npm audit
npm audit --json # JSON格式输出
npm audit --audit-level=moderate # 仅显示中等及以上风险
Fix vulnerabilities
修复漏洞
npm audit fix
npm audit fix --force # May install breaking changes
npm audit fix
npm audit fix --force # 可能安装破坏性更新
Yarn audit
Yarn审计
yarn audit
yarn audit --level moderate
yarn audit
yarn audit --level moderate
pnpm audit
pnpm审计
pnpm audit
pnpm audit --audit-level moderate
pnpm audit --fix
undefinedpnpm audit
pnpm audit --audit-level moderate
pnpm audit --fix
undefinedSecurity Best Practices
安全最佳实践
bash
undefinedbash
undefinedInstall specific vulnerability fixes
安装特定版本的漏洞修复包
npm install package@version
npm install package@version
Use npm-check-updates for safe updates
使用npm-check-updates进行安全更新
npx npm-check-updates
npx ncu -u # Update package.json
npm install
npx npm-check-updates
npx ncu -u # 更新package.json
npm install
Check for outdated packages
检查过时包
npm outdated
yarn outdated
pnpm outdated
npm outdated
yarn outdated
pnpm outdated
Use Snyk for deeper scanning
使用Snyk进行深度扫描
npx snyk test
npx snyk wizard
npx snyk test
npx snyk wizard
Ignore specific vulnerabilities (use cautiously)
忽略特定漏洞(谨慎使用)
Create .npmrc
创建.npmrc
echo "audit-level=moderate" >> .npmrc
undefinedecho "audit-level=moderate" >> .npmrc
undefinedWorkspace and Monorepo Management
工作区与单仓库管理
npm Workspaces
npm工作区
json
{
"name": "my-monorepo",
"private": true,
"workspaces": [
"packages/*",
"apps/*"
],
"scripts": {
"build": "npm run build --workspaces",
"test": "npm run test --workspaces",
"clean": "npm run clean --workspaces"
}
}bash
undefinedjson
{
"name": "my-monorepo",
"private": true,
"workspaces": [
"packages/*",
"apps/*"
],
"scripts": {
"build": "npm run build --workspaces",
"test": "npm run test --workspaces",
"clean": "npm run clean --workspaces"
}
}bash
undefinedInstall dependencies for all workspaces
为所有工作区安装依赖
npm install
npm install
Add dependency to specific workspace
为特定工作区添加依赖
npm install lodash --workspace=packages/utils
npm install lodash --workspace=packages/utils
Run script in specific workspace
在特定工作区运行脚本
npm run build --workspace=packages/utils
npm run build --workspace=packages/utils
Run script in all workspaces
在所有工作区运行脚本
npm run test --workspaces
npm run test --workspaces
List workspaces
列出工作区
npm ls --workspaces
undefinednpm ls --workspaces
undefinedYarn Workspaces
Yarn工作区
json
{
"name": "my-monorepo",
"private": true,
"workspaces": {
"packages": [
"packages/*",
"apps/*"
]
}
}bash
undefinedjson
{
"name": "my-monorepo",
"private": true,
"workspaces": {
"packages": [
"packages/*",
"apps/*"
]
}
}bash
undefinedInstall all dependencies
安装所有依赖
yarn install
yarn install
Add dependency to workspace
为工作区添加依赖
yarn workspace @myorg/utils add lodash
yarn workspace @myorg/utils add lodash
Run script in workspace
在工作区运行脚本
yarn workspace @myorg/utils build
yarn workspace @myorg/utils build
Run script in all workspaces
在所有工作区运行脚本
yarn workspaces run build
yarn workspaces run build
Show workspace info
查看工作区信息
yarn workspaces info
undefinedyarn workspaces info
undefinedpnpm Workspaces
pnpm工作区
yaml
undefinedyaml
undefinedpnpm-workspace.yaml
pnpm-workspace.yaml
packages:
- 'packages/*'
- 'apps/*'
```bashpackages:
- 'packages/*'
- 'apps/*'
```bashInstall all dependencies
安装所有依赖
pnpm install
pnpm install
Add dependency to workspace
为工作区添加依赖
pnpm add lodash --filter @myorg/utils
pnpm add lodash --filter @myorg/utils
Run script in workspace
在工作区运行脚本
pnpm --filter @myorg/utils build
pnpm --filter @myorg/utils build
Run script in all workspaces
在所有工作区运行脚本
pnpm -r build
pnpm -r build
Run in parallel
并行运行
pnpm -r --parallel build
undefinedpnpm -r --parallel build
undefinedCommon Issues & Solutions
常见问题与解决方案
Issue: Module Not Found
问题:模块未找到
bash
undefinedbash
undefinedCheck if package is installed
检查包是否已安装
npm list package-name
npm list package-name
Reinstall dependencies
重新安装依赖
rm -rf node_modules package-lock.json
npm install
rm -rf node_modules package-lock.json
npm install
Clear npm cache
清理npm缓存
npm cache clean --force
npm install
npm cache clean --force
npm install
Check NODE_PATH
检查NODE_PATH
echo $NODE_PATH
echo $NODE_PATH
Fix: Ensure package is in dependencies
修复:确保包已添加到依赖
npm install package-name
undefinednpm install package-name
undefinedIssue: Version Conflicts
问题:版本冲突
bash
undefinedbash
undefinedCheck for conflicts
检查冲突
npm ls package-name
npm ls package-name
Force resolution (package.json)
强制版本解析(package.json)
{
"overrides": {
"package-name": "1.2.3"
}
}
{
"overrides": {
"package-name": "1.2.3"
}
}
Yarn resolutions
Yarn版本解析
{
"resolutions": {
"package-name": "1.2.3"
}
}
{
"resolutions": {
"package-name": "1.2.3"
}
}
pnpm overrides
pnpm版本覆盖
{
"pnpm": {
"overrides": {
"package-name": "1.2.3"
}
}
}
undefined{
"pnpm": {
"overrides": {
"package-name": "1.2.3"
}
}
}
undefinedIssue: Peer Dependency Warnings
问题:对等依赖警告
bash
undefinedbash
undefinednpm 7+ treats peer dependencies as regular dependencies
npm 7+将对等依赖视为常规依赖
To use legacy behavior:
使用旧版行为:
npm install --legacy-peer-deps
npm install --legacy-peer-deps
Or set in .npmrc
或在.npmrc中设置
echo "legacy-peer-deps=true" >> .npmrc
echo "legacy-peer-deps=true" >> .npmrc
Install peer dependencies manually
手动安装对等依赖
npm install peer-dependency-name
undefinednpm install peer-dependency-name
undefinedIssue: EACCES Permission Errors
问题:EACCES权限错误
bash
undefinedbash
undefinedDon't use sudo! Fix permissions instead
不要使用sudo!请修复权限
Option 1: Change npm directory
方案1:修改npm目录
mkdir /.npm-global
npm config set prefix '/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
mkdir /.npm-global
npm config set prefix '/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
Option 2: Fix ownership
方案2:修复目录所有权
sudo chown -R $(whoami) ~/.npm
sudo chown -R $(whoami) /usr/local/lib/node_modules
undefinedsudo chown -R $(whoami) ~/.npm
sudo chown -R $(whoami) /usr/local/lib/node_modules
undefinedIssue: Corrupted node_modules
问题:node_modules损坏
bash
undefinedbash
undefinedComplete cleanup
完全清理
rm -rf node_modules package-lock.json
npm cache clean --force
npm install
rm -rf node_modules package-lock.json
npm cache clean --force
npm install
Verify installation
验证安装
npm list
npm doctor
npm list
npm doctor
Check disk space
检查磁盘空间
df -h
undefineddf -h
undefinedIssue: Slow Installation
问题:安装速度慢
bash
undefinedbash
undefinedUse pnpm (fastest)
使用pnpm(最快)
npm install -g pnpm
pnpm install
npm install -g pnpm
pnpm install
Use offline cache
使用离线缓存
npm install --prefer-offline
npm install --prefer-offline
Skip optional dependencies
跳过可选依赖
npm install --no-optional
npm install --no-optional
Parallel installation
并行安装
npm install --legacy-peer-deps
npm install --legacy-peer-deps
Use CI mode
使用CI模式
npm ci # Faster, uses lock file
undefinednpm ci # 速度更快,使用锁文件
undefinedPerformance Optimization
性能优化
.npmrc Configuration
.npmrc配置
bash
undefinedbash
undefined.npmrc file
.npmrc文件
registry=https://registry.npmjs.org/
save-exact=true
progress=false
loglevel=error
engine-strict=true
legacy-peer-deps=false
fund=false
audit=true
undefinedregistry=https://registry.npmjs.org/
save-exact=true
progress=false
loglevel=error
engine-strict=true
legacy-peer-deps=false
fund=false
audit=true
undefinedPackage Installation Optimization
包安装优化
bash
undefinedbash
undefinedUse npm ci in CI/CD (10x faster)
在CI/CD中使用npm ci(速度快10倍)
npm ci
npm ci
Skip post-install scripts (when safe)
跳过安装后脚本(安全情况下)
npm install --ignore-scripts
npm install --ignore-scripts
Use production mode
使用生产模式
npm install --production
npm install --production
Prefer offline
优先使用离线缓存
npm install --prefer-offline
npm install --prefer-offline
Use package manager cache
使用包管理器缓存
npm: ~/.npm
npm: ~/.npm
yarn: ~/.yarn/cache
yarn: ~/.yarn/cache
pnpm: ~/.pnpm-store
pnpm: ~/.pnpm-store
undefinedundefinedBundle Size Optimization
包体积优化
bash
undefinedbash
undefinedAnalyze bundle size
分析包体积
npx webpack-bundle-analyzer
npx webpack-bundle-analyzer
Check package size before installing
安装前检查包体积
npx package-size lodash moment date-fns
npx package-size lodash moment date-fns
Find duplicate packages
查找重复包
npx find-duplicate-packages
npx find-duplicate-packages
Use bundle size tools
使用包体积工具
npm install --save-dev bundle-size
npx bundle-size
npm install --save-dev bundle-size
npx bundle-size
Alternative: Use bundlephobia
替代方案:使用Bundlephobia
undefinedundefinedPublishing Packages
包发布
Prepare for Publishing
发布准备
json
{
"name": "@myorg/package-name",
"version": "1.0.0",
"description": "Package description",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"prepublishOnly": "npm run build && npm test",
"prepare": "npm run build"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}json
{
"name": "@myorg/package-name",
"version": "1.0.0",
"description": "包描述",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"prepublishOnly": "npm run build && npm test",
"prepare": "npm run build"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}Publishing Workflow
发布流程
bash
undefinedbash
undefinedLogin to npm
登录npm
npm login
npm login
Check what will be published
检查将发布的内容
npm pack --dry-run
npm pack --dry-run
Update 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 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
Publish
发布包
npm publish
npm publish
Publish scoped package
发布作用域包
npm publish --access public
npm publish --access public
Publish with tag
带标签发布
npm publish --tag beta
npm publish --tag beta
View published package
查看已发布包
npm view @myorg/package-name
undefinednpm view @myorg/package-name
undefinedMigration Between Package Managers
包管理器迁移
npm to Yarn
npm转Yarn
bash
undefinedbash
undefinedInstall Yarn
安装Yarn
npm install -g yarn
npm install -g yarn
Import from package-lock.json
从package-lock.json导入
yarn import
yarn import
Or fresh install
或重新安装
rm package-lock.json
yarn install
undefinedrm package-lock.json
yarn install
undefinednpm to pnpm
npm转pnpm
bash
undefinedbash
undefinedInstall pnpm
安装pnpm
npm install -g pnpm
npm install -g pnpm
Import from package-lock.json
从package-lock.json导入
pnpm import
pnpm import
Or fresh install
或重新安装
rm package-lock.json
pnpm install
undefinedrm package-lock.json
pnpm install
undefinedYarn to npm
Yarn转npm
bash
undefinedbash
undefinedRemove Yarn files
移除Yarn文件
rm yarn.lock
rm yarn.lock
Install with npm
使用npm安装
npm install
undefinednpm install
undefinedScripts and Automation
脚本与自动化
Complex Script Examples
复杂脚本示例
json
{
"scripts": {
"// Parallel execution": "",
"dev": "concurrently \"npm:dev:*\"",
"dev:server": "nodemon src/server.ts",
"dev:client": "vite",
"// Sequential execution": "",
"build": "npm run clean && npm run build:tsc && npm run build:bundle",
"build:tsc": "tsc",
"build:bundle": "webpack",
"// Cross-platform commands": "",
"clean": "rimraf dist",
"copy": "copyfiles -u 1 src/**/*.json dist",
"// Environment-specific": "",
"start:dev": "NODE_ENV=development node dist/index.js",
"start:prod": "NODE_ENV=production node dist/index.js",
"// With arguments": "",
"test": "jest",
"test:file": "jest --",
"// Usage: npm run test:file path/to/test.js"
}
}json
{
"scripts": {
"// 并行执行": "",
"dev": "concurrently \"npm:dev:*\"",
"dev:server": "nodemon src/server.ts",
"dev:client": "vite",
"// 顺序执行": "",
"build": "npm run clean && npm run build:tsc && npm run build:bundle",
"build:tsc": "tsc",
"build:bundle": "webpack",
"// 跨平台命令": "",
"clean": "rimraf dist",
"copy": "copyfiles -u 1 src/**/*.json dist",
"// 环境特定命令": "",
"start:dev": "NODE_ENV=development node dist/index.js",
"start:prod": "NODE_ENV=production node dist/index.js",
"// 带参数": "",
"test": "jest",
"test:file": "jest --",
"// 使用方式:npm run test:file path/to/test.js"
}
}Custom npm Scripts
自定义npm脚本
bash
undefinedbash
undefinedRun with npm run
使用npm run执行
npm run build
npm run build
Pass arguments
传递参数
npm run test -- --watch
npm run test:file -- src/utils.test.js
npm run test -- --watch
npm run test:file -- src/utils.test.js
Run multiple scripts
执行多个脚本
npm run build && npm test
npm run build && npm test
Run in parallel (with npm-run-all)
并行执行(需安装npm-run-all)
npm install --save-dev npm-run-all
npm-run-all --parallel dev:*
undefinednpm install --save-dev npm-run-all
npm-run-all --parallel dev:*
undefinedBest Practices Summary
最佳实践总结
Package Management
包管理
- Always commit lock files (package-lock.json, yarn.lock, pnpm-lock.yaml)
- Use exact versions in production ()
npm install --save-exact - Pin Node.js version with .nvmrc
- Use in CI/CD for faster, reliable installs
npm ci - Keep dependencies minimal (check bundle size)
- Separate dev and production dependencies
- 务必提交锁文件(package-lock.json、yarn.lock、pnpm-lock.yaml)到版本控制
- 生产环境使用精确版本()
npm install --save-exact - 使用.nvmrc固定Node.js版本
- CI/CD环境使用实现更快、更可靠的安装
npm ci - 尽量减少依赖(检查包体积)
- 区分开发依赖与生产依赖
Security
安全
- Run regularly
npm audit - Keep dependencies updated
- Review dependency changes before updating
- Use lock files for reproducible builds
- Don't commit node_modules or .env files
- Use instead of global installs when possible
npx
- 定期运行
npm audit - 保持依赖更新
- 更新前审查依赖变更
- 使用锁文件确保构建可复现
- 不要提交node_modules或.env文件
- 尽可能使用替代全局安装
npx
Performance
性能
- Use pnpm for fastest installation
- Leverage offline cache when possible
- Use in CI/CD
npm ci - Consider Yarn PnP for zero-installs
- Analyze and optimize bundle size
- 使用pnpm实现最快安装
- 尽可能利用离线缓存
- CI/CD环境使用
npm ci - 考虑使用Yarn PnP实现零安装
- 分析并优化包体积
Project Organization
项目组织
- Use clear, descriptive script names
- Document complex scripts in README
- Use workspaces for monorepos
- Follow semantic versioning
- Include engines field for Node version requirements
- 使用清晰、有描述性的脚本名称
- 在README中记录复杂脚本
- 单仓库项目使用工作区
- 遵循语义化版本规范
- 添加engines字段指定Node.js版本要求
Quick Reference Commands
快速参考命令
bash
undefinedbash
undefinedInstallation
安装
npm install # Install all dependencies
npm install <package> # Install package
npm install -D <package> # Install as dev dependency
npm install -g <package> # Install globally
npm ci # Clean install from lock file
npm install # 安装所有依赖
npm install <package> # 安装指定包
npm install -D <package> # 安装为开发依赖
npm install -g <package> # 全局安装
npm ci # 从锁文件干净安装
Updating
更新
npm update # Update all packages
npm update <package> # Update specific package
npm outdated # Check for outdated packages
npm update # 更新所有包
npm update <package> # 更新指定包
npm outdated # 检查过时包
Removal
移除
npm uninstall <package> # Remove package
npm prune # Remove unused packages
npm uninstall <package> # 移除指定包
npm prune # 移除未使用的包
Information
信息查询
npm list # List installed packages
npm view <package> # View package info
npm search <package> # Search for packages
npm list # 列出已安装包
npm view <package> # 查看包信息
npm search <package> # 搜索包
Scripts
脚本执行
npm run <script> # Run script
npm test # Run tests
npm start # Start app
npm run <script> # 运行指定脚本
npm test # 运行测试
npm start # 启动应用
Security
安全
npm audit # Check for vulnerabilities
npm audit fix # Fix vulnerabilities
npm audit # 检查漏洞
npm audit fix # 修复漏洞
Cache
缓存
npm cache clean --force # Clear cache
npm cache verify # Verify cache
npm cache clean --force # 清理缓存
npm cache verify # 验证缓存
Publishing
发布
npm login # Login to registry
npm publish # Publish package
npm version <type> # Bump version
undefinednpm login # 登录npm仓库
npm publish # 发布包
npm version <type> # 升级版本
undefinedNotes
注意事项
- Use npm ci in CI/CD for consistent, fast installs
- Always commit lock files to version control
- Prefer exact versions for production dependencies
- Use workspaces for monorepo management
- Regularly audit dependencies for security
- Keep Node.js and package managers updated
- Use .nvmrc to specify Node.js version
- Consider pnpm for better performance and disk usage
- Use semantic versioning for package releases
- Document all custom scripts in README
- CI/CD环境使用npm ci实现一致、快速的安装
- 务必将锁文件提交到版本控制
- 生产依赖优先使用精确版本
- 单仓库项目使用工作区管理
- 定期审计依赖安全性
- 保持Node.js与包管理器更新
- 使用.nvmrc指定Node.js版本
- 考虑使用pnpm提升性能与磁盘利用率
- 包发布遵循语义化版本规范
- 在README中记录所有自定义脚本