第一个 Deno 项目
从 main.ts、deno.json 和测试文件建立一个最小可维护项目
初始化项目:
deno init hello-deno
cd hello-deno
hello-deno/
├── deno.json
├── main.ts
└── main_test.ts
将 main.ts 改成一个可测试的处理函数:
export function handler(request: Request): Response {
const url = new URL(request.url);
return Response.json({ message: "Hello Deno", path: url.pathname });
}
if (import.meta.main) {
Deno.serve({ port: 8000 }, handler);
}
deno.json 记录团队命令:
{
"tasks": {
"dev": "deno run --watch --allow-net=0.0.0.0:8000 main.ts",
"check": "deno fmt --check && deno lint && deno check main.ts main_test.ts",
"test": "deno test"
}
}
deno task check
deno task test
deno task dev
Deno.serve 监听端口需要网络权限;单元测试直接调用 handler() 时不监听网络,因此测试不必使用 -A。