乐闻世界logo
搜索文章和话题

Deno 的生态系统有哪些流行的库和工具?

2月21日 16:08

Deno 的生态系统虽然相对年轻,但发展迅速,提供了丰富的第三方库和工具。了解 Deno 的生态系统有助于开发者更好地利用现有资源。

生态系统概述

Deno 的生态系统主要由以下几个部分组成:

  1. deno.land/x - 第三方模块注册表
  2. deno.land/std - 官方标准库
  3. nest.land - 另一个流行的模块注册表
  4. Deno Deploy - 官方边缘计算平台
  5. 社区工具和框架 - 各种开发工具和框架

流行的第三方库

1. Web 框架

Oak

typescript
import { Application, Router } from "https://deno.land/x/oak@v12.6.1/mod.ts"; const app = new Application(); const router = new Router(); router.get("/", (ctx) => { ctx.response.body = "Hello, Oak!"; }); router.get("/users/:id", (ctx) => { const { id } = ctx.params; ctx.response.body = { id, name: `User ${id}` }; }); app.use(router.routes()); app.use(router.allowedMethods()); await app.listen({ port: 8000 });

Fresh

typescript
import { Fresh } from "https://deno.land/x/fresh@1.4.0/server.ts"; import { handler } from "./routes/index.tsx"; const app = new Fresh(); app.get("/", handler); await app.listen({ port: 8000 });

Hono

typescript
import { Hono } from "https://deno.land/x/hono@v3.11.0/mod.ts"; const app = new Hono(); app.get("/", (c) => c.text("Hello, Hono!")); app.get("/users/:id", (c) => { const id = c.req.param("id"); return c.json({ id, name: `User ${id}` }); }); Deno.serve(app.fetch);

2. 数据库客户端

PostgreSQL (postgres)

typescript
import { Client } from "https://deno.land/x/postgres@v0.17.0/mod.ts"; const client = new Client({ user: "user", database: "database", hostname: "localhost", port: 5432, password: "password", }); await client.connect(); const result = await client.queryArray("SELECT * FROM users"); console.log(result.rows); await client.end();

MySQL (mysql)

typescript
import { Client } from "https://deno.land/x/mysql@v2.12.0/mod.ts"; const client = await new Client().connect({ hostname: "127.0.0.1", username: "root", password: "password", db: "test", }); const users = await client.query("SELECT * FROM users"); console.log(users); await client.close();

MongoDB (mongo)

typescript
import { MongoClient } from "https://deno.land/x/mongo@v0.31.0/mod.ts"; const client = new MongoClient(); await client.connect("mongodb://localhost:27017"); const db = client.database("test"); const users = db.collection<User>("users"); const user = await users.findOne({ name: "John" }); console.log(user); await client.close();

Redis (redis)

typescript
import { connect } from "https://deno.land/x/redis@v0.31.0/mod.ts"; const redis = await connect({ hostname: "127.0.0.1", port: 6379, }); await redis.set("key", "value"); const value = await redis.get("key"); console.log(value); await redis.close();

3. ORM 和查询构建器

DenoDB

typescript
import { Database } from "https://deno.land/x/denodb@v1.0.0/mod.ts"; const db = new Database("postgres", { host: "127.0.0.1", username: "user", password: "password", database: "test", }); class User extends Model { static fields = { id: { primaryKey: true, autoIncrement: true }, name: { type: VARCHAR }, email: { type: VARCHAR, unique: true }, }; } db.link([User]); await db.sync(); const user = await User.create({ name: "John", email: "john@example.com" }); console.log(user);

Drizzle ORM

typescript
import { drizzle } from "https://deno.land/x/drizzle@v0.5.0/mod.ts"; import { pgTable, serial, text, varchar } from "https://deno.land/x/drizzle@v0.5.0/pg-core/mod.ts"; const users = pgTable("users", { id: serial("id").primaryKey(), name: text("name").notNull(), email: varchar("email", { length: 255 }).notNull().unique(), }); const db = drizzle("postgresql://user:password@localhost:5432/test"); const user = await db.insert(users).values({ name: "John", email: "john@example.com", }).returning().get(); console.log(user);

4. 认证和授权

JWT (djwt)

typescript
import { create, verify, getNumericDate } from "https://deno.land/x/djwt@v3.0.1/mod.ts"; const key = await crypto.subtle.generateKey( { name: "HMAC", hash: "SHA-256" }, true, ["sign", "verify"] ); const payload = { iss: "my-app", exp: getNumericDate(60 * 60), // 1 hour data: { userId: 123 }, }; const token = await create({ alg: "HS256", typ: "JWT" }, payload, key); console.log("Token:", token); const verified = await verify(token, key); console.log("Verified:", verified);

OAuth (oauth2_client)

typescript
import { OAuth2Client } from "https://deno.land/x/oauth2_client@v1.0.2/mod.ts"; const oauth2Client = new OAuth2Client({ clientId: "your-client-id", clientSecret: "your-client-secret", authorizationEndpointUri: "https://github.com/login/oauth/authorize", tokenUri: "https://github.com/login/oauth/access_token", }); const authUrl = oauth2Client.code.getAuthorizationUri({ redirectUri: "http://localhost:8000/callback", scope: "read:user", }); console.log("Visit:", authUrl);

5. 工具库

Lodash (lodash)

typescript
import _ from "https://deno.land/x/lodash@4.17.19-es/mod.ts"; const users = [ { name: "John", age: 30 }, { name: "Jane", age: 25 }, ]; const sorted = _.orderBy(users, ["age"], ["asc"]); console.log(sorted); const names = _.map(users, "name"); console.log(names);

Date-fns (date_fns)

typescript
import { format, addDays, isAfter } from "https://deno.land/x/date_fns@v2.29.3/mod.ts"; const now = new Date(); const future = addDays(now, 7); console.log(format(now, "yyyy-MM-dd")); console.log(format(future, "yyyy-MM-dd")); console.log(isAfter(future, now));

Zod (zod)

typescript
import { z } from "https://deno.land/x/zod@v3.21.4/mod.ts"; const UserSchema = z.object({ id: z.number(), name: z.string().min(2), email: z.string().email(), age: z.number().min(0).max(120), }); const userData = { id: 1, name: "John", email: "john@example.com", age: 30, }; const user = UserSchema.parse(userData); console.log(user);

6. 测试工具

Supabase (supabase)

typescript
import { createClient } from "https://deno.land/x/supabase@2.0.0/mod.ts"; const supabase = createClient( "your-project-url", "your-anon-key" ); const { data, error } = await supabase .from("users") .select("*") .eq("id", 1); console.log(data);

开发工具

1. 代码格式化

Deno 内置了格式化工具:

bash
deno fmt .

2. 代码检查

bash
deno lint .

3. 文档生成

bash
deno doc --html --output=./docs ./src

4. 依赖检查

bash
deno info

包管理工具

1. Denoify

将 Node.js 包转换为 Deno 兼容的包:

bash
denoify

2. Deno 2 NPM (d2n)

将 npm 包转换为 Deno 模块:

bash
d2n express

3. Import Map Generator

自动生成 import map:

bash
deno run --allow-read --allow-write https://deno.land/x/import_map_generator/main.ts

部署平台

1. Deno Deploy

官方边缘计算平台:

typescript
// main.ts import { serve } from "https://deno.land/std@0.208.0/http/server.ts"; serve((req) => { return new Response("Hello from Deno Deploy!"); });

2. Vercel

支持 Deno 部署:

json
{ "builds": [ { "src": "main.ts", "use": "@vercel/deno" } ] }

3. Railway

支持 Deno 部署:

toml
[build] builder = "NIXPACKS" [deploy] startCommand = "deno run --allow-net main.ts"

社区资源

1. 官方资源

2. 社区论坛

3. 学习资源

最佳实践

1. 选择合适的库

  • 优先使用标准库
  • 选择活跃维护的第三方库
  • 查看库的文档和示例
  • 检查库的更新频率

2. 版本管理

typescript
// 指定具体版本 import { serve } from "https://deno.land/std@0.208.0/http/server.ts"; import { Application } from "https://deno.land/x/oak@v12.6.1/mod.ts";

3. 安全性

  • 检查库的安全性
  • 使用最小权限原则
  • 定期更新依赖

4. 性能

  • 选择性能优化的库
  • 避免不必要的依赖
  • 使用缓存策略

迁移指南

1. 从 Node.js 迁移

typescript
// Node.js const express = require('express'); const app = express(); // Deno import { Application } from "https://deno.land/x/oak@v12.6.1/mod.ts"; const app = new Application();

2. 使用兼容层

typescript
import { polyfill } from "https://deno.land/x/node_polyfills@v0.1.48/main.ts"; polyfill(); // 现在可以使用 Node.js API const fs = require('fs');

未来发展

Deno 生态系统正在快速发展,以下是一些值得关注的趋势:

  1. 更多第三方库:生态系统持续扩大
  2. 更好的工具支持:开发工具不断完善
  3. 企业级功能:更多企业级特性
  4. 性能优化:持续的性能改进
  5. 跨平台支持:更好的跨平台兼容性

Deno 的生态系统虽然年轻,但发展迅速,提供了丰富的资源和工具。通过合理利用这些资源,开发者可以更高效地构建应用程序。

标签:Deno