Node.js后端与现代前端的项目结构
一、全栈项目的组织方式
1.1 项目组织策略
单仓库多项目(Monorepo) 分离仓库(多仓库) 全栈单项目
二、Monorepo结构
project-root/
├── packages/
│ ├── backend/ # Node.js后端
│ │ ├── src/
│ │ ├── package.json
│ │ └── tsconfig.json
│ │
│ └── frontend/ # 前端应用
│ ├── src/
│ ├── public/
│ ├── package.json
│ └── vite.config.js
│
├── package.json # 工作区配置
├── lerna.json # Lerna配置(可选)
└── .gitignore
三、Node.js后端目录结构
3.1 基础结构
backend/
├── src/
│ ├── config/ # 配置文件
│ ├── controllers/ # 控制器
│ ├── models/ # 数据模型
│ ├── routes/ # 路由定义
│ ├── services/ # 业务逻辑
│ ├── utils/ # 工具函数
│ ├── middlewares/ # 中间件
│ └── app.js # 应用入口
│
├── tests/ # 测试文件
├── package.json # 依赖管理
├── tsconfig.json # TypeScript配置
├── .env # 环境变量
└── .gitignore
3.2 控制器示例
const UserService = require ( '../services/userService' ) ;
class UserController {
async getUsers ( req, res ) {
try {
const users = await UserService. findAll ( ) ;
res. status ( 200 ) . json ( users) ;
} catch ( error) {
res. status ( 500 ) . json ( { message: error. message } ) ;
}
}
async createUser ( req, res ) {
try {
const user = await UserService. create ( req. body) ;
res. status ( 201 ) . json ( user) ;
} catch ( error) {
res. status ( 400 ) . json ( { message: error. message } ) ;
}
}
}
module. exports = new UserController ( ) ;
四、现代前端目录结构
4.1 基础结构(React案例)
frontend/
├── src/
│ ├── assets/ # 静态资源
│ ├── components/ # 可复用组件
│ ├── pages/ # 页面组件
│ ├── hooks/ # 自定义钩子
│ ├── services/ # API服务
│ ├── store/ # 状态管理
│ ├── utils/ # 工具函数
│ ├── App.jsx # 应用根组件
│ └── main.jsx # 入口文件
│
├── public/ # 公共静态资源
├── index.html # HTML模板
├── package.json # 依赖管理
├── vite.config.js # 构建配置
└── .eslintrc.js # 代码规范配置
4.2 服务层示例
import axios from 'axios' ;
const api = axios. create ( {
baseURL: process. env. VITE_API_URL || 'http://localhost:3000/api' ,
timeout: 10000 ,
headers: {
'Content-Type' : 'application/json'
}
} ) ;
api. interceptors. request. use (
config => {
const token = localStorage. getItem ( 'token' ) ;
if ( token) {
config. headers. Authorization = ` Bearer ${ token} ` ;
}
return config;
} ,
error => Promise. reject ( error)
) ;
api. interceptors. response. use (
response => response. data,
error => {
if ( error. response && error. response. status === 401 ) {
window. location. href = '/login' ;
}
return Promise. reject ( error) ;
}
) ;
export default api;
五、共享代码与类型定义
5.1 共享目录结构
project-root/
├── packages/
│ ├── shared/ # 共享代码
│ │ ├── src/
│ │ │ ├── types/ # 共享类型定义
│ │ │ ├── utils/ # 共享工具函数
│ │ │ └── constants/ # 共享常量
│ │ └── package.json
│ ├── backend/ # 引用shared包
│ └── frontend/ # 引用shared包
5.2 共享类型示例
export interface User {
id: string ;
username: string ;
email: string ;
role: UserRole;
createdAt: Date;
updatedAt: Date;
}
export enum UserRole {
ADMIN = 'admin' ,
USER = 'user' ,
GUEST = 'guest'
}
export interface CreateUserDto {
username: string ;
email: string ;
password: string ;
}
六、环境配置
6.1 后端环境配置
# backend/.env.example
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://user:password@localhost:5432/dbname
JWT_SECRET=your_jwt_secret
CORS_ORIGIN=http://localhost:5173
6.2 前端环境配置
# frontend/.env.example
VITE_API_URL=http://localhost:3000/api
VITE_AUTH_DOMAIN=your-auth-domain
VITE_ENVIRONMENT=development
七、构建与部署配置
7.1 根目录package.json
{
"name" : "my-fullstack-app" ,
"private" : true ,
"workspaces" : [
"packages/*"
] ,
"scripts" : {
"start:backend" : "cd packages/backend && npm run start" ,
"start:frontend" : "cd packages/frontend && npm run dev" ,
"dev" : "concurrently \"npm run start:backend\" \"npm run start:frontend\"" ,
"build" : "npm run build --workspaces" ,
"test" : "npm run test --workspaces" ,
"lint" : "npm run lint --workspaces"
} ,
"devDependencies" : {
"concurrently" : "^8.0.0"
}
}
八、Docker化配置
8.1 Docker Compose示例
version : '3.8'
services :
backend :
build :
context : ./packages/backend
ports :
- "3000:3000"
environment :
- NODE_ENV=production
- DATABASE_URL=postgres: //user: password@db: 5432/dbname
depends_on :
- db
frontend :
build :
context : ./packages/frontend
ports :
- "80:80"
depends_on :
- backend
db :
image : postgres: 14
environment :
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
- POSTGRES_DB=dbname
volumes :
- postgres_data: /var/lib/postgresql/data
volumes :
postgres_data :