Express MVC
1. 安装依赖
npm init -y
npm install express
npm install --save-dev typescript ts-node ejs @types/node @types/express
tsc --init
2. 项目目录结构如下,没有的手动创建
/my-app
/src
/models
user.ts
/views
index.ejs
userList.ejs
/controllers
userController.ts
/routes
userRoutes.ts
/public
/css
/js
app.ts
tsconfig.json
3. TypeScript 配置 (tsconfig.json)
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true, // 兼容 esm 和 commonjs
"forceConsistentCasingInFileNames": true, // 导入时大小写必须一致
"strict": true // 启用 ts 的严格类型检查
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
4. 代码实现
app.ts (主应用文件)
import express from 'express';
import path from 'path';
import userRoutes from './routes/userRoutes';
const app = express();
// 设置视图引擎为 EJS,参数名称固定写法,不可以随意更改
app.set('view engine', 'ejs');
// 设置视图文件夹位置
app.set('views', path.join(__dirname, 'views'));
// 设置静态文件夹
app.use(express.static(path.join(__dirname, 'public')));
// 解析请求体
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// 使用路由
app.use('/users', userRoutes);
// 根路由
app.get('/', (req, res) => {
res.render('index', { title: 'Express + TypeScript MVC' });
});
// 启动服务器
const port = 3000;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
models/user.ts (模型)
export interface User {
id: number;
name: string;
email: string;
}
export const getUsers = (): User[] => {
return [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Doe', email: 'jane@example.com' },
];
};
controllers/userController.ts (控制器)
import { Request, Response } from 'express';
import { getUsers } from '../models/user';
export const getUserList = (req: Request, res: Response) => {
const users = getUsers();
res.render('userList', { users });
};
routes/userRoutes.ts (路由)
import express from 'express';
import { getUserList } from '../controllers/userController';
const router = express.Router();
// 用户列表路由
router.get('/', getUserList);
export default router;
views/index.ejs (视图)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<%= title %>
</title>
</head>
<body>
<h1>Welcome to Express + TypeScript MVC!</h1>
<a href="/users">Go to Users</a>
</body>
</html>
views/userList.ejs (显示用户列表的视图)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<ul>
<% users.forEach(user=> { %>
<li>
<%= user.name %> - <%= user.email %>
</li>
<% }) %>
</ul>
<a href="/">Back to Home</a>
</body>
</html>
5. 运行项目
在 package.json 中设置启动脚本:
"scripts": {
"start": "ts-node src/app.ts"
},
启动应用
npm run start