用 TypeScript 编写 Node.js 后端可以大幅提升可维护性和开发效率。本文覆盖 TS + Node 的工程化全流程。
一、项目初始化
mkdir my-api && cd my-api
npm init -y
npm install -D typescript ts-node nodemon @types/node
npx tsc --init
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
}
}
二、Express + TS
import express, { Request, Response } from 'express';
const app = express();
interface User {
id: number;
name: string;
}
app.get('/users/:id', (req: Request<{ id: string }>, res: Response<User>) => {
const user: User = { id: Number(req.params.id), name: 'Alice' };
res.json(user);
});
app.listen(3000);
三、Nest.js(推荐企业级)
Nest.js 原生基于 TypeScript 设计,是 Node.js 的 Angular 式框架:
npm install -g @nestjs/cli
nest new my-project
// user.controller.ts
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get(':id')
async findOne(@Param('id') id: string): Promise<User> {
return this.userService.findById(id);
}
}
四、开发工具链
# 热重载
dev: "nodemon --exec ts-node src/index.ts"
# 测试
npm install -D jest ts-jest @types/jest
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
};
五、Prisma 类型安全 ORM
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// 完全类型安全的查询
const user = await prisma.user.findUnique({
where: { id: 1 },
include: { posts: true },
});
// user 的类型自动推断为 User & { posts: Post[] }
相关阅读
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。