Appearance
npm 最佳实践
npm最佳实践涵盖了从项目初始化到包发布的各个方面。本章将详细介绍npm开发中的最佳实践和指导原则。
项目初始化最佳实践
项目结构
json
{
"name": "well-structured-project",
"version": "1.0.0",
"description": "A well-structured npm project",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./utils": {
"import": "./dist/utils.mjs",
"require": "./dist/utils.js"
}
},
"files": [
"dist/",
"README.md",
"LICENSE"
]
}
项目初始化脚本
bash
#!/bin/bash
# scripts/init-project.sh
# 创建项目目录结构
mkdir -p src/{components,utils,types,__tests__}
mkdir -p docs scripts config
# 初始化package.json
npm init -y
# 安装开发依赖
npm install -D typescript eslint prettier husky lint-staged
# 创建配置文件
touch .gitignore .npmignore .prettierrc .eslintrc.json tsconfig.json
# 配置husky
npx husky install
npx husky add .husky/pre-commit "npx lint-staged"
echo "Project initialized successfully!"
版本管理最佳实践
语义化版本控制
json
{
"version": "1.0.0",
"scripts": {
"version:major": "npm version major -m 'Release v%s'",
"version:minor": "npm version minor -m 'Release v%s'",
"version:patch": "npm version patch -m 'Release v%s'",
"version:prerelease": "npm version prerelease --preid=beta -m 'Beta release v%s'",
"preversion": "npm test && npm run build",
"version": "git add -A src/",
"postversion": "git push && git push --tags && echo 'Publish with: npm publish'"
},
"engines": {
"node": ">=16.14.0",
"npm": ">=8.0.0"
}
}
版本策略
json
{
"dependencies": {
// 使用^确保安全更新
"express": "^4.18.0",
// 框架相关使用~或固定版本
"react": "^18.0.0",
"react-dom": "^18.0.0",
// 关键依赖使用固定版本
"critical-lib": "1.2.3"
},
"devDependencies": {
// 开发依赖可以使用^
"jest": "^28.0.0",
"webpack": "^5.72.0"
}
}
依赖管理最佳实践
依赖分类
json
{
"dependencies": {
// 生产环境运行必需
"express": "^4.18.0",
"lodash": "^4.17.21"
},
"devDependencies": {
// 开发和构建时需要
"jest": "^28.0.0",
"webpack": "^5.72.0",
"eslint": "^8.0.0",
"prettier": "^2.0.0",
"@types/node": "^18.0.0"
},
"peerDependencies": {
// 期望宿主环境提供
"react": "^17.0.0 || ^18.0.0"
},
"optionalDependencies": {
// 可选依赖
"fsevents": "^2.3.2"
}
}
依赖审查流程
json
{
"scripts": {
"deps:check": "npx depcheck && npx npm-check",
"deps:outdated": "npm outdated",
"deps:audit": "npm audit --audit-level moderate",
"deps:size": "npx bundlephobia-cli --all",
"validate:deps": "npm run deps:check && npm run deps:audit"
}
}
安全最佳实践
安全配置
json
{
"scripts": {
"security:check": "npm audit --audit-level moderate",
"security:ci": "npm audit --audit-level low --json | npx @npmcli/audit-report",
"security:lock": "npm audit --audit-level low && npm ci"
},
"engines": {
"node": ">=16.14.0",
"npm": ">=8.0.0"
}
}
账户安全
bash
# 设置2FA
npm profile enable-2fa auth-and-writes
# 使用访问令牌
npm token create --read-only --cidr=192.168.0.1/24
# 配置.npmrc
echo "engine-strict=true" >> .npmrc
echo "audit=true" >> .npmrc
echo "audit-level=moderate" >> .npmrc
工作区最佳实践
Monorepo结构
json
{
"name": "my-monorepo",
"private": true,
"workspaces": [
"packages/*",
"apps/*",
"shared/*"
],
"scripts": {
"build": "npm run build --workspaces --if-present",
"test": "npm run test --workspaces --if-present",
"lint": "npm run lint --workspaces --if-present",
"dev": "concurrently \"npm run dev --workspace=app-frontend\" \"npm run dev --workspace=app-backend\"",
"clean": "npm run clean --workspaces --if-present && rimraf node_modules"
},
"devDependencies": {
"concurrently": "^7.0.0"
}
}
工作区依赖管理
json
// packages/shared/package.json
{
"name": "@my-org/shared",
"version": "1.0.0",
"main": "dist/index.js",
"files": [
"dist/"
]
}
json
// apps/frontend/package.json
{
"name": "frontend",
"version": "1.0.0",
"dependencies": {
"@my-org/shared": "workspace:*"
}
}
脚本最佳实践
脚本组织
json
{
"scripts": {
// 构建相关
"build": "tsc && vite build",
"build:dev": "tsc --watch & vite build --mode development",
"build:prod": "vite build --mode production",
"build:analyze": "vite build --mode analyze",
// 开发相关
"dev": "vite",
"dev:api": "nodemon src/api/server.js",
"dev:ui": "vite --host",
// 测试相关
"test": "jest",
"test:unit": "jest --testPathPattern=unit",
"test:integration": "jest --testPathPattern=integration",
"test:e2e": "playwright test",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
// 质量相关
"lint": "eslint src/ --ext .js,.ts,.jsx,.tsx",
"lint:fix": "eslint src/ --ext .js,.ts,.jsx,.tsx --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"type-check": "tsc --noEmit",
"validate": "npm run type-check && npm run lint && npm run test",
// 工具相关
"clean": "rimraf dist coverage node_modules/.cache",
"clean:install": "npm run clean && rm package-lock.json && npm install",
// 发布相关
"prepublishOnly": "npm run build && npm run test",
"version": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md",
"postversion": "git push && git push --tags"
}
}
脚本钩子
json
{
"scripts": {
"prebuild": "npm run clean",
"postbuild": "npm run integrity-check",
"pretest": "npm run type-check",
"posttest": "npm run report-coverage",
"prepublishOnly": "npm run validate",
"postpublish": "echo 'Published successfully! Don\\'t forget to update docs.'"
}
}
配置最佳实践
.npmrc配置
# 性能优化
maxsockets=50
fetch-retry-mintimeout=10000
fetch-retry-maxtimeout=60000
# 安全设置
audit=true
audit-level=moderate
engine-strict=true
# 用户体验
progress=true
loglevel=warn
# 开发友好
fund=false
sign-git-tag=true
# 工作区
prefer-offline=true
package.json配置
json
{
"name": "my-package",
"version": "1.0.0",
"description": "A well-configured npm package",
"keywords": [
"javascript",
"util",
"helper"
],
"homepage": "https://github.com/user/my-package#readme",
"bugs": {
"url": "https://github.com/user/my-package/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/user/my-package.git"
},
"license": "MIT",
"author": "Your Name <your.email@example.com>",
"sideEffects": false,
"engines": {
"node": ">=16.14.0"
},
"publishConfig": {
"access": "public"
}
}
CI/CD最佳实践
GitHub Actions
yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [16.x, 18.x, 20.x]
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
env:
CI: true
- name: Run tests
run: npm test -- --ci --coverage
env:
CI: true
- name: Run linting
run: npm run lint
env:
CI: true
- name: Run type checking
run: npm run type-check
env:
CI: true
- name: Run security audit
run: npm audit --audit-level moderate
env:
CI: true
yaml
# .github/workflows/release.yml
name: Release
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: write
id-token: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
registry-url: 'https://registry.npmjs.org/'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build
- name: Publish
run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create Release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false
发布最佳实践
发布前检查清单
json
{
"scripts": {
"release:check": "npm run validate && npm run security:check && npm run test:coverage",
"release:prepare": "npm run release:check && npm run build && npm pack --dry-run",
"release:patch": "npm run release:prepare && npm version patch && npm publish",
"release:minor": "npm run release:prepare && npm version minor && npm publish",
"release:major": "npm run release:prepare && npm version major && npm publish"
}
}
npmignore最佳实践
# 依赖目录
node_modules/
# 构建目录
dist/
build/
.coverage/
# 日志文件
*.log
npm-debug.log*
# IDE文件
.vscode/
.idea/
*.swp
*.swo
# 临时文件
.DS_Store
Thumbs.db
# 测试文件(除非需要)
tests/
__tests__/
# 开发文件
*.test.js
*.spec.js
# 配置文件(非必需)
*.config.js
.eslintrc.js
性能优化最佳实践
安装优化
bash
# 使用npm ci进行可重现构建(推荐用于生产)
npm ci
# 使用npm ci在CI环境中
npm ci --no-audit --no-fund
# 离线安装
npm install --prefer-offline
# 生产环境安装
npm install --production
缓存策略
json
{
"scripts": {
"cache:verify": "npm cache verify",
"cache:clean": "npm cache clean --force",
"install:fast": "npm install --prefer-offline --no-audit --no-fund"
}
}
团队协作最佳实践
标准化配置
json
{
"devDependencies": {
"husky": "^8.0.0",
"lint-staged": "^13.0.0",
"@commitlint/cli": "^17.0.0",
"@commitlint/config-conventional": "^17.0.0"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write",
"git add"
],
"*.{json,md}": [
"prettier --write",
"git add"
]
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}
贡献指南
markdown
# 贡献指南
## 开发环境设置
```bash
# 克隆项目
git clone <repository-url>
cd project-name
# 安装依赖
npm install
# 验证安装
npm run validate
代码规范
- 使用Prettier格式化代码
- 遵循ESLint规则
- 提交信息遵循Conventional Commits规范
分支策略
main: 生产就绪代码develop: 开发主分支feature/*: 功能分支hotfix/*: 紧急修复分支
提交规范
提交信息格式:
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
类型包括:
- feat: 新功能
- fix: 修复bug
- docs: 文档更新
- style: 代码格式调整
- refactor: 重构
- perf: 性能优化
- test: 测试相关
- chore: 构建过程或辅助工具的变动
## 故障排除最佳实践
### 问题诊断脚本
```json
{
"scripts": {
"debug:env": "node -e \"console.log({node: process.version, npm: process.env.npm_config_user_agent, platform: process.platform})\"",
"debug:deps": "npm ls --depth=0",
"debug:cache": "npm config get cache && npm cache verify",
"debug:config": "npm config list",
"troubleshoot": "npm run debug:env && npm run debug:deps && npm run debug:config"
}
}
清理脚本
json
{
"scripts": {
"nuke": "rm -rf node_modules package-lock.json && npm install",
"clean:all": "npm run clean && npm cache clean --force && rm -rf node_modules package-lock.json",
"reset": "npm run clean:all && npm install && npm run build"
}
}
文档最佳实践
package.json文档
json
{
"name": "well-documented-package",
"version": "1.0.0",
"description": "A package that follows documentation best practices",
"main": "dist/index.js",
"scripts": {
"docs:generate": "typedoc src/",
"docs:serve": "npx serve docs/",
"docs:deploy": "gh-pages -d docs/"
},
"keywords": [
"javascript",
"util",
"functional"
],
"repository": {
"type": "git",
"url": "https://github.com/user/well-documented-package.git"
},
"bugs": {
"url": "https://github.com/user/well-documented-package/issues"
},
"homepage": "https://github.com/user/well-documented-package#readme"
}
通过遵循这些最佳实践,您可以确保npm项目的质量、安全性和可维护性。