developer-onboarding
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDeveloper Onboarding
开发者入职文档
Overview
概述
Create comprehensive onboarding documentation that helps new developers quickly set up their development environment, understand the codebase, and start contributing effectively.
创建全面的入职文档,帮助新开发者快速搭建开发环境、了解代码库并高效开始贡献代码。
When to Use
适用场景
- New developer onboarding
- README file creation
- Contributing guidelines
- Development environment setup
- Architecture overview docs
- Code style guides
- Git workflow documentation
- Testing guidelines
- Deployment procedures
- 新开发者入职
- README文件创建
- 贡献准则制定
- 开发环境设置
- 架构概述文档
- 代码风格指南
- Git工作流文档
- 测试准则
- 部署流程
Comprehensive README Template
全面的README模板
markdown
undefinedmarkdown
undefinedProject Name
项目名称
Table of Contents
目录
Features
功能特性
- ✨ Feature 1: Brief description
- 🚀 Feature 2: Brief description
- 🔒 Feature 3: Brief description
- 📊 Feature 4: Brief description
- ✨ 功能1:简要说明
- 🚀 功能2:简要说明
- 🔒 功能3:简要说明
- 📊 功能4:简要说明
Quick Start
快速开始
Get up and running in less than 5 minutes:
bash
undefined5分钟内快速启动项目:
bash
undefinedClone the repository
克隆仓库
git clone https://github.com/username/repo.git
cd repo
git clone https://github.com/username/repo.git
cd repo
Install dependencies
安装依赖
npm install
npm install
Set up environment
设置环境变量
cp .env.example .env
cp .env.example .env
Run database migrations
运行数据库迁移
npm run db:migrate
npm run db:migrate
Start development server
启动开发服务器
npm run dev
Visit [http://localhost:3000](http://localhost:3000) to see the app.npm run dev
访问 [http://localhost:3000](http://localhost:3000) 查看应用。Prerequisites
前置要求
Installation
安装步骤
1. Clone the Repository
1. 克隆仓库
bash
git clone https://github.com/username/repo.git
cd repobash
git clone https://github.com/username/repo.git
cd repo2. Install Dependencies
2. 安装依赖
bash
undefinedbash
undefinedInstall all dependencies
安装所有依赖
npm install
npm install
Or use yarn
或使用yarn
yarn install
yarn install
Or use pnpm
或使用pnpm
pnpm install
undefinedpnpm install
undefined3. Set Up Environment Variables
3. 设置环境变量
Create a file in the root directory:
.envbash
cp .env.example .envEdit and configure the following:
.envenv
undefined在根目录创建 文件:
.envbash
cp .env.example .env编辑 并配置以下内容:
.envenv
undefinedApplication
应用配置
NODE_ENV=development
PORT=3000
BASE_URL=http://localhost:3000
NODE_ENV=development
PORT=3000
BASE_URL=http://localhost:3000
Database
数据库配置
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
Redis
Redis配置
REDIS_URL=redis://localhost:6379
REDIS_URL=redis://localhost:6379
Authentication
认证配置
JWT_SECRET=your-secret-key-here
JWT_EXPIRES_IN=7d
JWT_SECRET=your-secret-key-here
JWT_EXPIRES_IN=7d
External APIs
外部API配置
STRIPE_SECRET_KEY=sk_test_...
SENDGRID_API_KEY=SG...
STRIPE_SECRET_KEY=sk_test_...
SENDGRID_API_KEY=SG...
AWS (if applicable)
AWS配置(如适用)
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=your-key
AWS_SECRET_ACCESS_KEY=your-secret
S3_BUCKET_NAME=your-bucket
undefinedAWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=your-key
AWS_SECRET_ACCESS_KEY=your-secret
S3_BUCKET_NAME=your-bucket
undefined4. Database Setup
4. 数据库设置
bash
undefinedbash
undefinedCreate database
创建数据库
createdb your_database_name
createdb your_database_name
Run migrations
运行迁移
npm run db:migrate
npm run db:migrate
Seed database with sample data (optional)
(可选)向数据库填充示例数据
npm run db:seed
undefinednpm run db:seed
undefined5. Verify Installation
5. 验证安装
bash
undefinedbash
undefinedRun tests to verify setup
运行测试验证设置
npm test
npm test
Start development server
启动开发服务器
npm run dev
If everything is set up correctly, you should see:✓ Server running on http://localhost:3000
✓ Database connected
✓ Redis connected
undefinedConfiguration
配置说明
Database Configuration
数据库配置
Edit :
config/database.jsjavascript
module.exports = {
development: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
logging: console.log,
},
test: {
url: process.env.TEST_DATABASE_URL,
dialect: 'postgres',
logging: false,
},
production: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
logging: false,
pool: {
max: 20,
min: 5,
acquire: 30000,
idle: 10000,
},
},
};编辑 :
config/database.jsjavascript
module.exports = {
development: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
logging: console.log,
},
test: {
url: process.env.TEST_DATABASE_URL,
dialect: 'postgres',
logging: false,
},
production: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
logging: false,
pool: {
max: 20,
min: 5,
acquire: 30000,
idle: 10000,
},
},
};Application Configuration
应用配置
Main config file:
config/app.jsjavascript
module.exports = {
port: process.env.PORT || 3000,
env: process.env.NODE_ENV || 'development',
apiVersion: 'v1',
rateLimit: {
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
},
cors: {
origin: process.env.CORS_ORIGIN || '*',
credentials: true,
},
};主配置文件:
config/app.jsjavascript
module.exports = {
port: process.env.PORT || 3000,
env: process.env.NODE_ENV || 'development',
apiVersion: 'v1',
rateLimit: {
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 限制每个IP在窗口时间内最多100次请求
},
cors: {
origin: process.env.CORS_ORIGIN || '*',
credentials: true,
},
};Development
开发指南
Project Structure
项目结构
.
├── src/
│ ├── api/ # API routes
│ │ ├── controllers/ # Route controllers
│ │ ├── middlewares/ # Express middlewares
│ │ └── routes/ # Route definitions
│ ├── config/ # Configuration files
│ ├── models/ # Database models
│ ├── services/ # Business logic
│ ├── utils/ # Utility functions
│ └── app.js # Express app setup
├── tests/
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── scripts/ # Utility scripts
├── docs/ # Documentation
├── .env.example # Environment template
├── .eslintrc.js # ESLint config
├── .prettierrc # Prettier config
├── package.json
└── README.md.
├── src/
│ ├── api/ # API路由
│ │ ├── controllers/ # 路由控制器
│ │ ├── middlewares/ # Express中间件
│ │ └── routes/ # 路由定义
│ ├── config/ # 配置文件
│ ├── models/ # 数据库模型
│ ├── services/ # 业务逻辑
│ ├── utils/ # 工具函数
│ └── app.js # Express应用设置
├── tests/
│ ├── unit/ # 单元测试
│ ├── integration/ # 集成测试
│ └── e2e/ # 端到端测试
├── scripts/ # 工具脚本
├── docs/ # 文档
├── .env.example # 环境变量模板
├── .eslintrc.js # ESLint配置
├── .prettierrc # Prettier配置
├── package.json
└── README.mdAvailable Scripts
可用脚本
bash
undefinedbash
undefinedDevelopment
开发相关
npm run dev # Start dev server with hot reload
npm run dev:debug # Start with debugger attached
npm run dev # 启动带热重载的开发服务器
npm run dev:debug # 启动调试模式
Building
构建相关
npm run build # Build for production
npm run build:watch # Build and watch for changes
npm run build # 生产环境构建
npm run build:watch # 构建并监听文件变化
Testing
测试相关
npm test # Run all tests
npm run test:unit # Run unit tests only
npm run test:integration # Run integration tests
npm run test:e2e # Run e2e tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Generate coverage report
npm test # 运行所有测试
npm run test:unit # 仅运行单元测试
npm run test:integration # 运行集成测试
npm run test:e2e # 运行端到端测试
npm run test:watch # 监听模式运行测试
npm run test:coverage # 生成测试覆盖率报告
Linting & Formatting
代码检查与格式化
npm run lint # Run ESLint
npm run lint:fix # Fix ESLint errors
npm run format # Format code with Prettier
npm run format:check # Check formatting
npm run lint # 运行ESLint检查
npm run lint:fix # 自动修复ESLint错误
npm run format # 使用Prettier格式化代码
npm run format:check # 检查代码格式化情况
Database
数据库相关
npm run db:migrate # Run migrations
npm run db:migrate:undo # Undo last migration
npm run db:seed # Seed database
npm run db:reset # Reset database (drop, create, migrate, seed)
npm run db:migrate # 运行迁移
npm run db:migrate:undo # 回滚上一次迁移
npm run db:seed # 填充数据库
npm run db:reset # 重置数据库(删除、创建、迁移、填充)
Other
其他
npm run clean # Clean build artifacts
npm start # Start production server
undefinednpm run clean # 清理构建产物
npm start # 启动生产服务器
undefinedCode Style
代码风格
We use ESLint and Prettier for consistent code style:
ESLint Config:
javascript
// .eslintrc.js
module.exports = {
extends: ['airbnb-base', 'prettier'],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
},
};Prettier Config:
json
{
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 100,
"tabWidth": 2
}我们使用ESLint和Prettier保证代码风格一致:
ESLint配置:
javascript
// .eslintrc.js
module.exports = {
extends: ['airbnb-base', 'prettier'],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
},
};Prettier配置:
json
{
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 100,
"tabWidth": 2
}Git Workflow
Git工作流
Create feature branch
创建功能分支
git checkout -b feature/your-feature-name
git checkout -b feature/your-feature-name
Make changes and commit
提交变更
git add .
git commit -m "feat: add new feature"
git add .
git commit -m "feat: add new feature"
Push to remote
推送到远程仓库
git push origin feature/your-feature-name
git push origin feature/your-feature-name
Create pull request on GitHub
在GitHub上创建拉取请求
**Branch Naming Convention:**
- `feature/` - New features
- `bugfix/` - Bug fixes
- `hotfix/` - Urgent production fixes
- `refactor/` - Code refactoring
- `docs/` - Documentation updates
**Commit Message Convention:**
We use [Conventional Commits](https://www.conventionalcommits.org/):
type(scope): subject
body
footer
**Types:**
- `feat:` - New feature
- `fix:` - Bug fix
- `docs:` - Documentation changes
- `style:` - Code style changes (formatting, etc.)
- `refactor:` - Code refactoring
- `test:` - Adding or updating tests
- `chore:` - Maintenance tasks
**Examples:**
```bash
feat(auth): add OAuth2 authentication
fix(api): resolve race condition in order processing
docs(readme): update installation instructions
**分支命名规范:**
- `feature/` - 新功能
- `bugfix/` - Bug修复
- `hotfix/` - 紧急生产修复
- `refactor/` - 代码重构
- `docs/` - 文档更新
**提交信息规范:**
我们使用 [Conventional Commits](https://www.conventionalcommits.org/):
type(scope): subject
body
footer
**类型说明:**
- `feat:` - 新功能
- `fix:` - Bug修复
- `docs:` - 文档变更
- `style:` - 代码风格变更(如格式化)
- `refactor:` - 代码重构
- `test:` - 添加或更新测试
- `chore:` - 维护任务
**示例:**
```bash
feat(auth): add OAuth2 authentication
fix(api): resolve race condition in order processing
docs(readme): update installation instructionsTesting
测试流程
Running Tests
运行测试
bash
undefinedbash
undefinedRun all tests
运行所有测试
npm test
npm test
Run with coverage
生成覆盖率报告
npm run test:coverage
npm run test:coverage
Run specific test file
运行指定测试文件
npm test -- tests/unit/user.test.js
npm test -- tests/unit/user.test.js
Run tests matching pattern
运行匹配指定模式的测试
npm test -- --grep "User API"
undefinednpm test -- --grep "User API"
undefinedWriting Tests
编写测试
Unit Test Example:
javascript
// tests/unit/user.service.test.js
const { expect } = require('chai');
const UserService = require('../../src/services/user.service');
describe('UserService', () => {
describe('createUser', () => {
it('should create a new user', async () => {
const userData = {
email: 'test@example.com',
password: 'password123',
name: 'Test User',
};
const user = await UserService.createUser(userData);
expect(user).to.have.property('id');
expect(user.email).to.equal(userData.email);
expect(user.password).to.not.equal(userData.password); // Should be hashed
});
it('should throw error for duplicate email', async () => {
const userData = { email: 'existing@example.com' };
await expect(UserService.createUser(userData)).to.be.rejectedWith(
'Email already exists'
);
});
});
});Integration Test Example:
javascript
// tests/integration/auth.test.js
const request = require('supertest');
const app = require('../../src/app');
describe('Auth API', () => {
describe('POST /api/auth/register', () => {
it('should register a new user', async () => {
const response = await request(app)
.post('/api/auth/register')
.send({
email: 'newuser@example.com',
password: 'password123',
name: 'New User',
})
.expect(201);
expect(response.body).to.have.property('token');
expect(response.body.user).to.have.property('id');
});
});
});单元测试示例:
javascript
// tests/unit/user.service.test.js
const { expect } = require('chai');
const UserService = require('../../src/services/user.service');
describe('UserService', () => {
describe('createUser', () => {
it('should create a new user', async () => {
const userData = {
email: 'test@example.com',
password: 'password123',
name: 'Test User',
};
const user = await UserService.createUser(userData);
expect(user).to.have.property('id');
expect(user.email).to.equal(userData.email);
expect(user.password).to.not.equal(userData.password); // 密码应已加密
});
it('should throw error for duplicate email', async () => {
const userData = { email: 'existing@example.com' };
await expect(UserService.createUser(userData)).to.be.rejectedWith(
'Email already exists'
);
});
});
});集成测试示例:
javascript
// tests/integration/auth.test.js
const request = require('supertest');
const app = require('../../src/app');
describe('Auth API', () => {
describe('POST /api/auth/register', () => {
it('should register a new user', async () => {
const response = await request(app)
.post('/api/auth/register')
.send({
email: 'newuser@example.com',
password: 'password123',
name: 'New User',
})
.expect(201);
expect(response.body).to.have.property('token');
expect(response.body.user).to.have.property('id');
});
});
});Deployment
部署方法
Production Build
生产环境构建
bash
undefinedbash
undefinedBuild for production
生产环境构建
npm run build
npm run build
Start production server
启动生产服务器
NODE_ENV=production npm start
undefinedNODE_ENV=production npm start
undefinedDocker Deployment
Docker部署
dockerfile
undefineddockerfile
undefinedDockerfile
Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
```bashFROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
```bashBuild Docker image
构建Docker镜像
docker build -t myapp:latest .
docker build -t myapp:latest .
Run container
运行容器
docker run -p 3000:3000 --env-file .env myapp:latest
undefineddocker run -p 3000:3000 --env-file .env myapp:latest
undefinedEnvironment Variables
生产环境变量
Ensure these are set in production:
env
NODE_ENV=production
DATABASE_URL=postgresql://...
REDIS_URL=redis://...
JWT_SECRET=strong-random-secret确保生产环境已设置以下变量:
env
NODE_ENV=production
DATABASE_URL=postgresql://...
REDIS_URL=redis://...
JWT_SECRET=strong-random-secret... other production configs
... 其他生产配置
undefinedundefinedArchitecture
架构概述
High-Level Overview
高层架构
┌─────────────┐
│ Client │
└──────┬──────┘
│
▼
┌─────────────┐
│ API Gateway │
└──────┬──────┘
│
▼
┌─────────────┐ ┌──────────┐
│ Services │────▶│ Database │
└──────┬──────┘ └──────────┘
│
▼
┌─────────────┐
│ Cache │
└─────────────┘┌─────────────┐
│ 客户端 │
└──────┬──────┘
│
▼
┌─────────────┐
│ API网关 │
└──────┬──────┘
│
▼
┌─────────────┐ ┌──────────┐
│ 服务层 │────▶│ 数据库 │
└──────┬──────┘ └──────────┘
│
▼
┌─────────────┐
│ 缓存层 │
└─────────────┘Key Components
核心组件
- API Layer: Express.js REST API
- Service Layer: Business logic
- Data Layer: PostgreSQL + Redis
- Authentication: JWT-based auth
- Caching: Redis for session and data caching
- API层:Express.js REST API
- 服务层:业务逻辑实现
- 数据层:PostgreSQL + Redis
- 认证系统:基于JWT的认证
- 缓存系统:Redis用于会话和数据缓存
Contributing
贡献指南
We welcome contributions! Please see CONTRIBUTING.md for details.
我们欢迎所有贡献!详情请查看 CONTRIBUTING.md。
Quick Contribution Guide
快速贡献步骤
- Fork the repository
- Create your feature branch
- Make your changes
- Write/update tests
- Ensure all tests pass
- Submit a pull request
- Fork本仓库
- 创建你的功能分支
- 提交变更
- 编写/更新测试
- 确保所有测试通过
- 提交拉取请求
Code Review Process
代码评审流程
- All PRs require at least one approval
- CI must pass (tests, linting)
- Code coverage must not decrease
- Documentation must be updated
- 所有拉取请求至少需要一个批准
- CI必须通过(测试、代码检查)
- 代码覆盖率不得下降
- 文档必须同步更新
License
许可证
This project is licensed under the MIT License - see the LICENSE file for details.
本项目采用MIT许可证 - 详情请查看 LICENSE 文件。
Support
支持
- Documentation: https://docs.example.com
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Slack: Join our Slack
- 文档:https://docs.example.com
- 问题反馈:GitHub Issues
- 讨论区:GitHub Discussions
- Slack社区:加入我们的Slack
Acknowledgments
致谢
- List contributors
- Credit third-party libraries
- Thank sponsors
undefined- 贡献者列表
- 第三方库致谢
- 赞助商致谢
undefinedBest Practices
最佳实践
✅ DO
✅ 建议
- Start with a clear, concise project description
- Include badges for build status, coverage, etc.
- Provide a quick start section
- Document all prerequisites clearly
- Include troubleshooting section
- Keep README up-to-date
- Use code examples liberally
- Add architecture diagrams
- Document environment variables
- Include contribution guidelines
- Specify code style requirements
- Document testing procedures
- 从清晰简洁的项目简介开始
- 添加构建状态、覆盖率等徽章
- 提供快速开始章节
- 清晰记录所有前置要求
- 添加故障排除章节
- 保持README内容更新
- 大量使用代码示例
- 添加架构图
- 记录环境变量
- 包含贡献指南
- 指定代码风格要求
- 记录测试流程
❌ DON'T
❌ 避免
- Assume prior knowledge
- Skip prerequisite documentation
- Forget to update after major changes
- Use overly technical jargon
- Skip example code
- Ignore Windows/Mac/Linux differences
- Forget to document scripts
- 假设用户已有相关知识
- 跳过前置要求文档
- 重大变更后不更新文档
- 使用过于专业的术语
- 跳过示例代码
- 忽略Windows/Mac/Linux的差异
- 不记录脚本用途