使用 TypeScript 开发 Archy 服务器
安装依赖项
要开始开发 Archy,请先安装所需的依赖项:
npm install typescript ts-node nodemon @types/node @types/express --save-dev
安装 TypeScript
使用以下命令全局安装 TypeScript 和类型定义文件:
npm install -g typescript typescript@latest
编写配置文件
创建并编辑 tsconfig.json
文件,添加以下内容:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"strict": true,
"outDir": "build",
"declaration": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "build"]
}
运行开发模式
在开发环境中运行服务器时,可以使用以下命令:
npm run dev
该命令会自动重新加载服务器以响应文件更改。
编译 TypeScript 项目
使用以下方法运行 TypeScript 编译器:
使用本地安装的 TypeScript
npx tsc
要指定 tsconfig.json
文件,可以执行:
npx tsc --project tsconfig.json
要启用观察模式(实时重新编译),请运行:
npx tsc --watch
使用全局安装的 TypeScript
如果已将 TypeScript 全局安装,请执行以下命令:
tsc
常见 TypeScript 编译选项
--outDir <directory>
:指定输出目录。
--target <ES 版本>
:指定 ECMAScript 目标版本(例如 ES2020)。
--module <模块系统>
:指定模块系统(例如 NodeNext)。
--declaration
:生成 .d.ts
声明文件。
--sourceMap
:生成源映射文件以支持调试。
项目结构
src/
:TypeScript 源文件
src/index.ts
:程序入口点和服务器实现
src/server.ts
:服务器实现
src/generators/
:图表生成逻辑
src/utils/
:工具函数和辅助函数
build/
:编译输出的 JavaScript 文件
examples/
:示例使用脚本
test/
:测试文件
使用 Archy 生成图表
示例:从文本生成类图
generate_diagram_from_text({
"description": "为图书馆系统创建一个包含 Book、Author 和 Library 类的类图。书籍有标题和 ISBN。作者有姓名并可以编写多本书。图书馆馆藏包含书籍。",
"language": "zh-CN"
});
示例:从 URL 生成图表
generate_diagram_from_url({
"url": "https://example.com",
"language": "zh-CN"
});
配置开发环境
在 package.json
中添加以下内容:
{
"name": "archy-server",
"version": "1.0.0",
"scripts": {
"dev": "ts-node src/index.ts"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"typescript": "^5.0.2",
"ts-node": "^10.9.2",
"nodemon": "^3.0.2",
"@types/node": "^20.10.0",
"@types/express": "^4.18.1"
}
}
运行服务器
启动开发服务器:
npm run dev
开发模式功能
启用调试日志
在 tsconfig.json
中添加以下内容以启用调试日志:
{
"compilerOptions": {
"traceResolution": true,
"verbose": true
}
}
常见问题排查
-
模块解析错误
确保项目根目录中存在 tsconfig.json
文件,并且 include
和 exclude
配置正确。
-
无法启动服务器
检查安装是否成功:
npm list -g typescript ts-node nodemon
代码示例
简单 HTTP 服务器
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`应用运行在 http://localhost:${port}`);
});
带有路由的服务器
import express from 'express';
const router = express.Router();
router.get('/api', (req, res) => {
res.json({ message: 'Hello API' });
});
const app = express();
app.use('/', router);
const port = 3000;
app.listen(port, () => {
console.log(`应用运行在 http://localhost:${port}`);
});
进阶功能
配置代理
编辑 tsconfig.json
添加以下内容:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
然后在代码中使用模块路径:
import { generate_diagram_from_text } from '@';
配置 TypeScript 模块分辨率
编辑 tsconfig.json
添加以下内容:
{
"compilerOptions": {
"moduleResolution": "node",
"baseUrl": "."
}
}
总结
通过遵循上述步骤,您可以成功设置和开发一个使用 TypeScript 的 Archy 服务器。