引言:为什么选择 TypeScript 进行模块化开发?
在现代前端开发中,随着项目规模的不断增长,代码的可维护性、可扩展性和类型安全变得至关重要。TypeScript 作为 JavaScript 的超集,不仅提供了静态类型检查,还通过其强大的模块系统,为构建大型项目提供了坚实的基础。
TypeScript 模块化的优势
类型安全
:在模块间传递数据时,TypeScript 能够确保类型的一致性
更好的 IDE 支持
:智能提示、自动补全和重构支持
代码组织
:清晰的模块边界,避免命名冲突
编译时错误检查
:在代码运行前发现潜在问题
易于重构
:类型系统让大规模重构变得安全可靠
第一章:TypeScript 模块系统基础
1.1 理解 ES6 模块与 TypeScript 模块
TypeScript 使用 ES6 模块语法,但在编译时可以转换为不同的模块格式。
导出语法详解
// 1. 命名导出 (Named Exports)
// math.ts
export const PI = 3.14159;
export function add(a: number, b: number): number {
return a + b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
// 2. 默认导出 (Default Export)
// logger.ts
export default function logger(message: string): void {
console.log(`[${new Date().toISOString()}] ${message}`);
}
// 3. 重导出 (Re-export)
// index.ts
export { add, multiply } from ‘./math’;
export { default as log } from ‘./logger’;
导入语法详解
// 1. 命名导入
import { add, multiply } from ‘./math’;
// 2. 默认导入
import logger from ‘./logger’;
// 3. 命名空间导入(将所有导出放入一个对象)
import * as MathUtils from ‘./math’;
// 4. 混合导入
import logger, { add, multiply } from ‘./math’;
// 5. 别名导入
import { add as sum } from ‘./math’;
// 6. 动态导入(用于代码分割)
async function loadMathModule() {
const math = await import(‘./math’);
return math.add(1, 2);
}
1.2 TypeScript 特有的模块解析配置
在
tsconfig.json
中,模块解析配置对大型项目至关重要:
{
“compilerOptions”: {
“module”: “ESNext”, // 目标模块系统
“moduleResolution”: “Node”, // 模块解析策略
“baseUrl”: “./src”, // 基础路径
“paths”: { // 路径别名
“@utils/*”: [“utils/*”],
“@components/*”: [“components/*”],
“@services/*”: [“services/*”]
},
“rootDir”: “./src”, // 根目录
“outDir”: “./dist” // 输出目录
}
}
第二章:项目架构设计
2.1 经典的分层架构模式
对于大型项目,推荐采用分层架构:
src/
├── core/ # 核心业务逻辑
│ ├── entities/ # 实体类
│ ├── services/ # 业务服务
│ └── repositories/ # 数据访问层
├── infrastructure/ # 基础设施
│ ├── api/ # API 调用
│ ├── database/ # 数据库操作
│ └── cache/ # 缓存管理
├── presentation/ # 表现层
│ ├── components/ # 通用组件
│ ├── pages/ # 页面组件
│ └── hooks/ # 自定义 Hooks
├── shared/ # 共享模块
│ ├── types/ # 类型定义
│ ├── utils/ # 工具函数
│ └── constants/ # 常量定义
└── index.ts # 入口文件
2.2 基于功能的模块化架构
对于功能驱动的项目,推荐使用特性优先的架构:
src/
├── features/
│ ├── auth/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ └── index.ts
│ ├── dashboard/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ └── index.ts
│ └── settings/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ └── index.ts
├── shared/ # 跨特性共享
└── app.ts # 应用入口
第三章:类型定义与接口设计
3.1 集中式类型管理
在大型项目中,类型定义应该被精心组织:
// src/shared/types/index.ts
export * from ‘./user’;
export * from ‘./api’;
export * from ‘./common’;
// src/shared/types/user.ts
export interface User {
id: string;
name: string;
email: string;
role: UserRole;
createdAt: Date;
updatedAt: Date;
}
export enum UserRole {
ADMIN = ‘ADMIN’,
USER = ‘USER’,
GUEST = ‘GUEST’
}
export interface UserProfile extends User {
bio?: string;
avatar?: string;
preferences: UserPreferences;
}
export interface UserPreferences {
theme: ‘light’ | ‘dark’;
notifications: boolean;
language: string;
}
3.2 使用类型守卫(Type Guards)
// 类型守卫示例
export function isAdmin(user: User): user is User & { role: UserRole.ADMIN } {
return user.role === UserRole.ADMIN;
}
// 使用示例
function handleUserAction(user: User) {
if (isAdmin(user)) {
// 在这里,TypeScript 知道 user 具有 ADMIN 特权
user.role // UserRole.ADMIN
// 可以调用管理员特有方法
}
}
3.3 条件类型与高级类型
// 条件类型示例
type ApiResponse
data: T;
success: boolean;
message?: string;
};
// 映射类型示例
type ReadonlyUser = Readonly
type PartialUser = Partial
type RequiredUser = Required
// 工具类型组合
type UserUpdatePayload = Pick
type UserCreationPayload = Omit
第四章:模块间通信与依赖管理
4.1 依赖注入模式
在大型项目中,依赖注入可以帮助管理复杂的依赖关系:
// 依赖注入容器
type Constructor
class Container {
private services = new Map
private instances = new Map
register
this.services.set(token, constructor);
}
resolve
if (!this.instances.has(token)) {
const Constructor = this.services.get(token);
if (!Constructor) {
throw new Error(`Service ${token} not registered`);
}
this.instances.set(token, new Constructor());
}
return this.instances.get(token);
}
}
// 使用示例
interface ILogger {
log(message: string): void;
}
class ConsoleLogger implements ILogger {
log(message: string): void {
console.log(message);
}
}
class UserService {
constructor(private logger: ILogger) {}
createUser(name: string): void {
this.logger.log(`Creating user: ${name}`);
}
}
// 注册和使用
const container = new Container();
container.register(‘Logger’, ConsoleLogger);
container.register(‘UserService’, UserService);
const userService = container.resolve
4.2 事件总线模式
// 事件总线实现
type EventHandler = (data: any) => void;
class EventBus {
private events = new Map
on(event: string, handler: EventHandler): void {
if (!this.events.has(event)) {
this.events.set(event, []);
}
this.events.get(event)!.push(handler);
}
emit(event: string, data: any): void {
const handlers = this.events.get(event);
if (handlers) {
handlers.forEach(handler => handler(data));
}
}
off(event: string, handler: EventHandler): void {
const handlers = this.events.get(event);
if (handlers) {
const index = handlers.indexOf(handler);
if (index > -1) {
handlers.splice(index, 1);
}
}
}
}
// 使用示例
const bus = new EventBus();
// 模块A:监听事件
bus.on(‘user:created’, (user) => {
console.log(‘New user created:’, user);
});
// 模块B:触发事件
bus.emit(‘user:created’, { id: 1, name: ‘Alice’ });
第五章:实际项目构建实战
5.1 项目初始化与配置
步骤1:创建项目结构
mkdir my-ts-project
cd my-ts-project
npm init -y
步骤2:安装依赖
# 基础依赖
npm install typescript ts-node @types/node
# 开发依赖
npm install -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint prettier
# 运行时依赖(如果需要)
npm install express axios
步骤3:配置 TypeScript
创建
tsconfig.json
:
{
“compilerOptions”: {
“target”: “ES2020”,
“module”: “CommonJS”,
“lib”: [“ES2020”],
“outDir”: “./dist”,
“rootDir”: “./src”,
“strict”: true,
“esModuleInterop”: true,
“skipLibCheck”: true,
“forceConsistentCasingInFileNames”: true,
“resolveJsonModule”: true,
“moduleResolution”: “Node”,
“baseUrl”: “./src”,
“paths”: {
“@/*”: [“*”]
},
“declaration”: true,
“declarationMap”: true,
“sourceMap”: true
},
“include”: [“src/**/*”],
“exclude”: [“node_modules”, “dist”]
}
步骤4:配置 ESLint
创建
.eslintrc.js
:
module.exports = {
root: true,
parser: ‘@typescript-eslint/parser’,
plugins: [
‘@typescript-eslint’,
],
extends: [
‘eslint:recommended’,
‘@typescript-eslint/recommended’,
],
rules: {
‘@typescript-eslint/no-explicit-any’: ‘off’,
‘@typescript-eslint/explicit-module-boundary-types’: ‘off’,
},
env: {
node: true,
es6: true,
},
};
5.2 构建一个用户管理系统
5.2.1 核心实体定义
// src/core/entities/user.entity.ts
export class User {
constructor(
public readonly id: string,
public name: string,
public email: string,
public readonly createdAt: Date,
public readonly updatedAt: Date
) {}
updateProfile(name: string, email: string): void {
this.name = name;
this.email = email;
this.updatedAt = new Date();
}
getSummary(): string {
return `${this.name} (${this.email})`;
}
}
// src/core/entities/role.entity.ts
export enum Role {
ADMIN = ‘ADMIN’,
MODERATOR = ‘MODERATOR’,
USER = ‘USER’,
}
export class UserRole {
constructor(
public readonly userId: string,
public readonly role: Role,
public readonly assignedAt: Date
) {}
}
5.2.2 数据访问层
// src/infrastructure/database/interfaces/user.repository.ts
import { User } from ‘@/core/entities/user.entity’;
import { Role } from ‘@/core/entities/role.entity’;
export interface IUserRepository {
findById(id: string): Promise
findByEmail(email: string): Promise
findAll(): Promise
save(user: User): Promise
delete(id: string): Promise
assignRole(userId: string, role: Role): Promise
}
// src/infrastructure/database/repositories/user.repository.ts
import { IUserRepository } from ‘@/infrastructure/database/interfaces/user.repository’;
import { User } from ‘@/core/entities/user.entity’;
import { Role } from ‘@/core/entities/role.entity’;
// 模拟数据库
const userDB: Map
const userRolesDB: Map
export class UserRepository implements IUserRepository {
async findById(id: string): Promise
return userDB.get(id) || null;
}
async findByEmail(email: string): Promise
for (const user of userDB.values()) {
if (user.email === email) {
return user;
}
}
return null;
}
async findAll(): Promise
return Array.from(userDB.values());
}
async save(user: User): Promise
userDB.set(user.id, user);
return user;
}
async delete(id: string): Promise
return userDB.delete(id);
}
async assignRole(userId: string, role: Role): Promise
userRolesDB.set(userId, role);
}
}
5.2.3 业务服务层
// src/core/services/user.service.ts
import { IUserRepository } from ‘@/infrastructure/database/interfaces/user.repository’;
import { User } from ‘@/core/entities/user.entity’;
import { Role } from ‘@/core/entities/role.entity’;
import { v4 as uuidv4 } from ‘uuid’;
export class UserService {
constructor(private userRepository: IUserRepository) {}
async createUser(name: string, email: string): Promise
// 验证邮箱是否已存在
const existingUser = await this.userRepository.findByEmail(email);
if (existingUser) {
throw new Error(‘Email already exists’);
}
const user = new User(
uuidv4(),
name,
email,
new Date(),
new Date()
);
return await this.userRepository.save(user);
}
async getUserById(id: string): Promise
return await this.userRepository.findById(id);
}
async updateUser(id: string, name: string, email: string): Promise
const user = await this.userRepository.findById(id);
if (!user) {
return null;
}
user.updateProfile(name, email);
return await this.userRepository.save(user);
}
async deleteUser(id: string): Promise
return await this.userRepository.delete(id);
}
async assignAdminRole(userId: string): Promise
const user = await this.userRepository.findById(userId);
if (!user) {
throw new Error(‘User not found’);
}
await this.userRepository.assignRole(userId, Role.ADMIN);
}
}
5.2.4 API 控制器层
// src/presentation/controllers/user.controller.ts
import { Request, Response } from ‘express’;
import { UserService } from ‘@/core/services/user.service’;
export class UserController {
constructor(private userService: UserService) {}
async createUser(req: Request, res: Response): Promise
try {
const { name, email } = req.body;
const user = await this.userService.createUser(name, email);
res.status(201).json({ success: true, data: user });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
}
async getUser(req: Request, res: Response): Promise
try {
const { id } = req.params;
const user = await this.userService.getUserById(id);
if (!user) {
res.status(404).json({ success: false, error: ‘User not found’ });
return;
}
res.json({ success: true, data: user });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
}
async updateUser(req: Request, res: Response): Promise
try {
const { id } = req.params;
const { name, email } = req.body;
const user = await this.userService.updateUser(id, name, email);
if (!user) {
res.status(404).json({ success: false, error: ‘User not found’ });
return;
}
res.json({ success: true, data: user });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
}
async deleteUser(req: Request, res: Response): Promise
try {
const { id } = req.params;
const success = await this.userService.deleteUser(id);
if (!success) {
res.status(404).json({ success: false, error: ‘User not found’ });
return;
}
res.json({ success: true, message: ‘User deleted successfully’ });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
}
}
5.2.5 路由配置
// src/presentation/routes/user.routes.ts
import { Router } from ‘express’;
import { UserController } from ‘@/presentation/controllers/user.controller’;
import { UserService } from ‘@/core/services/user.service’;
import { UserRepository } from ‘@/infrastructure/database/repositories/user.repository’;
const router = Router();
const userRepository = new UserRepository();
const userService = new UserService(userRepository);
const userController = new UserController(userService);
router.post(‘/’, (req, res) => userController.createUser(req, res));
router.get(‘/:id’, (req, res) => userController.getUser(req, res));
router.put(‘/:id’, (req, res) => userController.updateUser(req, res));
router.delete(‘/:id’, (req, res) => userController.deleteUser(req, res));
export default router;
5.2.6 应用入口
// src/app.ts
import express from ‘express’;
import userRoutes from ‘@/presentation/routes/user.routes’;
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// 注册路由
app.use(‘/api/users’, userRoutes);
// 健康检查
app.get(‘/health’, (req, res) => {
res.json({ status: ‘OK’, timestamp: new Date().toISOString() });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
第六章:高级模块化技巧
6.1 使用 Barrel 模式简化导入
Barrel 模式通过在模块目录中创建索引文件来简化导入:
// src/shared/utils/index.ts
export * from ‘./validation.utils’;
export * from ‘./date.utils’;
export * from ‘./string.utils’;
// src/shared/utils/validation.utils.ts
export function isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
export function isNonEmptyString(str: string): boolean {
return typeof str === ‘string’ && str.trim().length > 0;
}
// 使用 Barrel 模式后,可以这样导入:
import { isValidEmail, isNonEmptyString } from ‘@/shared/utils’;
6.2 动态导入与代码分割
// 动态导入示例
async function loadAdminDashboard() {
try {
const { AdminDashboard } = await import(
/* webpackChunkName: “admin-dashboard” */
‘@/presentation/pages/AdminDashboard’
);
return AdminDashboard;
} catch (error) {
console.error(‘Failed to load admin dashboard:’, error);
throw error;
}
}
// 在 React 中使用
import React, { Suspense, lazy } from ‘react’;
const AdminDashboard = lazy(() => import(‘@/presentation/pages/AdminDashboard’));
function App() {
return (