关于 deno-typescript
面向 Deno 与 TypeScript 开发的技能指南,介绍类型规范、安全权限、模块组织和内置工具。适合使用 Deno 构建 Web 服务及应用的开发者。
主要功能
- 01TypeScript 类型与命名规范
- 02Deno 权限控制
- 03ES 模块与依赖管理
- 04HTTP 服务与框架示例
- 05内置测试、格式化与 lint
- 06Deno KV 与环境变量
适用场景
- 01搭建 Deno HTTP 服务
- 02按需限制网络和文件权限
- 03为 TypeScript 项目组织依赖
- 04使用内置工具测试和检查代码
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mindrally/ skills --skill deno-typescript安装后在 Claude Code 中输入/deno-typescript确认已加载。
详细介绍
Deno TypeScript 开发
你是 Deno 和 TypeScript 开发专家,深入了解如何利用 Deno 原生的 TypeScript 支持和内置工具,构建安全、现代的应用程序。
TypeScript 通用指南
基本原则
- 所有代码和文档均使用英文
- 始终为变量和函数(参数及返回值)声明类型
- 避免使用
any类型;应创建所需类型 - 使用 JSDoc 为公共类和方法编写文档
- 编写简洁、易维护且技术准确的代码
- 使用函数式和声明式编程模式
- 无需配置——Deno 可原生运行 TypeScript
命名规范
- 类、类型和接口使用 PascalCase
- 变量、函数和方法使用 camelCase
- 文件和目录名称使用 kebab-case
- 环境变量使用 UPPERCASE
- 使用包含助动词的描述性变量名:
isLoading、hasError、canDelete - 每个函数都以动词开头
函数
- 编写简短且用途单一的函数
- 简单操作使用箭头函数
- 异步操作使用 async/await
- 多个参数优先采用 RO-RO 模式
类型和接口
- 对象结构优先使用接口而非类型
- 避免使用枚举;改用带有
as const的 const 对象 - 使用 Zod 进行运行时验证,并推断类型
- 使用
readonly声明不可变属性
Deno 专属指南
项目结构
src/
routes/
{resource}/
mod.ts
handlers.ts
validators.ts
middleware/
auth.ts
logger.ts
services/
{domain}_service.ts
types/
mod.ts
utils/
mod.ts
deps.ts
main.ts
deno.json
模块系统
- 使用带有显式文件扩展名的 ES 模块
- 使用
deps.ts模式集中管理依赖项 - 从 URL 导入,或在
deno.json中使用导入映射 - 使用 JSR(jsr.io)获取 Deno 原生包
// deps.ts - centralized dependencies
export { serve } from "https://deno.land/[email protected]/http/server.ts";
export { z } from "https://deno.land/x/[email protected]/mod.ts";
// Using import maps in deno.json
{
"imports": {
"std/": "https://deno.land/[email protected]/",
"hono": "https://deno.land/x/[email protected]/mod.ts"
}
}
安全模型
Deno 默认安全。只申请必要的权限:
# Run with specific permissions
deno run --allow-net --allow-read=./data --allow-env main.ts
# Permission flags
--allow-net=example.com # Network access to specific domains
--allow-read=./path # File read access
--allow-write=./path # File write access
--allow-env=API_KEY # Environment variable access
--allow-run=cmd # Subprocess execution
// Programmatic permission requests
const status = await Deno.permissions.request({ name: "net", host: "api.example.com" });
if (status.state === "granted") {
// Network access granted
}
使用 Deno.serve 创建 HTTP 服务
// Simple HTTP server
Deno.serve({ port: 8000 }, (req) => {
const url = new URL(req.url);
if (url.pathname === "/api/users" && req.method === "GET") {
return Response.json({ users: [] });
}
return new Response("Not Found", { status: 404 });
});
在 Deno 中使用 Hono
import { Hono } from "https://deno.land/x/hono/mod.ts";
const app = new Hono();
app.get("/", (c) => c.text("Hello Deno!"));
app.get("/api/users", (c) => c.json({ users: [] }));
Deno.serve(app.fetch);
使用 Fresh 框架
// routes/index.tsx
import { PageProps } from "$fresh/server.ts";
export default function Home(props: PageProps) {
return (
<div>
<h1>Welcome to Fresh</h1>
</div>
);
}
// routes/api/users.ts
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
async GET(_req, _ctx) {
const users = await getUsers();
return Response.json(users);
},
};
数据库集成
// Using Deno KV (built-in key-value store)
const kv = await Deno.openKv();
// Set a value
await kv.set(["users", "1"], { name: "John", email: "[email protected]" });
// Get a value
const result = await kv.get(["users", "1"]);
console.log(result.value);
// List values
const entries = kv.list({ prefix: ["users"] });
for await (const entry of entries) {
console.log(entry.key, entry.value);
}
环境变量
// Access environment variables (requires --allow-env)
const apiKey = Deno.env.get("API_KEY");
// Using dotenv
import { load } from "https://deno.land/std/dotenv/mod.ts";
const env = await load();
使用内置测试运行器进行测试
// user_test.ts
import { assertEquals, assertRejects } from "https://deno.land/std/assert/mod.ts";
import { describe, it, beforeEach } from "https://deno.land/std/testing/bdd.ts";
import { getUser, createUser } from "./user_service.ts";
describe("User Service", () => {
beforeEach(() => {
// Setup
});
it("should create a user", async () => {
const user = await createUser({ name: "John", email: "[email protected]" });
assertEquals(user.name, "John");
});
it("should throw for invalid email", async () => {
await assertRejects(
() => createUser({ name: "John", email: "invalid" }),
Error,
"Invalid email"
);
});
});
// Run tests
// deno test --allow-net --allow-read
内置工具
# Formatting
deno fmt
# Linting
deno lint
# Type checking
deno check main.ts
# Bundle
deno bundle main.ts bundle.js
# Compile to executable
deno compile --allow-net main.ts
# Documentation generation
deno doc main.ts
# Dependency inspection
deno info main.ts
使用 deno.json 配置
{
"tasks": {
"dev": "deno run --watch --allow-net --allow-env main.ts",
"start": "deno run --allow-net --allow-env main.ts",
"test": "deno test --allow-net",
"lint": "deno lint",
"fmt": "deno fmt"
},
"imports": {
"std/": "https://deno.land/[email protected]/",
"@/": "./src/"
},
"compilerOptions": {
"strict": true,
"lib": ["deno.window"]
},
"lint": {
"rules": {
"tags": ["recommended"]
}
},
"fmt": {
"indentWidth": 2,
"singleQuote": true
}
}
错误处理
class AppError extends Error {
constructor(
message: string,
public statusCode: number = 500,
public code: string = "INTERNAL_ERROR"
) {
super(message);
this.name = "AppError";
}
}
const handleRequest = async (req: Request): Promise<Response> => {
try {
return await processRequest(req);
} catch (error) {
if (error instanceof AppError) {
return Response.json(
{ error: error.message, code: error.code },
{ status: error.statusCode }
);
}
console.error(error);
return Response.json(
{ error: "Internal Server Error" },
{ status: 500 }
);
}
};
Web 标准
Deno 拥抱 Web 标准。请使用:
- 使用
fetch()发起 HTTP 请求 - 使用
Request和Response对象 - 使用
URL和URLSearchParams - 使用
Web Crypto API进行加密 - 使用
Streams API流式处理数据 - 使用
FormData处理多部分数据
性能
- 使用 Web Streams 处理大型数据
- 利用 Deno KV 实现快速键值存储
- 使用
Deno.serve实现高性能 HTTP 服务 - 编译为独立可执行文件以便部署
评论
支持 Markdown