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

Deno 有哪些内置工具?如何使用它们?

2月18日 22:22

Deno 提供了一套完整的内置工具链,使得开发者无需安装额外的工具就能完成格式化、测试、linting、打包等开发任务。这些工具都集成在 Deno CLI 中,使用简单且高效。

内置工具概览

Deno 的内置工具包括:

  1. deno fmt - 代码格式化
  2. deno lint - 代码检查
  3. deno test - 测试运行
  4. deno compile - 编译为可执行文件
  5. deno bundle - 打包为单个文件
  6. deno doc - 生成文档
  7. deno bench - 性能基准测试

代码格式化 (deno fmt)

基本用法

bash
# 格式化当前目录所有文件 deno fmt # 格式化指定文件 deno fmt src/main.ts # 检查格式(不修改文件) deno fmt --check # 使用特定配置 deno fmt --options-line-width=100

配置选项

bash
# 设置行宽 deno fmt --options-line-width=120 # 设置缩进 deno fmt --options-indent-width=2 # 使用单引号 deno fmt --options-single-quote # 使用分号 deno fmt --options-use-tabs

示例

typescript
// 格式化前 const name="Deno"; function hello(name:string){ console.log(`Hello,${name}!`); } // 格式化后 const name = "Deno"; function hello(name: string) { console.log(`Hello, ${name}!`); }

代码检查 (deno lint)

基本用法

bash
# 检查当前目录 deno lint # 检查指定文件 deno lint src/main.ts # 自动修复问题 deno lint --fix # 忽略特定规则 deno lint --ignore=no-unused-vars

配置规则

bash
# 使用配置文件 deno lint --config=deno.json # 排除文件 deno lint --exclude=**/*.test.ts # 查看所有规则 deno lint --rules

常见规则

typescript
// 错误示例 function foo() { var x = 1; // no-var: 使用 let 或 const const unused = 2; // no-unused-vars: 未使用的变量 } // 正确示例 function foo() { const x = 1; return x; }

测试 (deno test)

基本用法

bash
# 运行所有测试 deno test # 运行指定测试文件 deno test src/main_test.ts # 监听模式(文件变化时自动运行) deno test --watch # 显示详细输出 deno test --verbose # 并行运行测试 deno test --parallel

编写测试

typescript
// math_test.ts import { assertEquals, assertThrows } from "https://deno.land/std@0.208.0/testing/asserts.ts"; function add(a: number, b: number): number { return a + b; } function divide(a: number, b: number): number { if (b === 0) { throw new Error("Division by zero"); } return a / b; } Deno.test("add function adds two numbers", () => { assertEquals(add(1, 2), 3); assertEquals(add(-1, 1), 0); }); Deno.test("divide function divides numbers", () => { assertEquals(divide(10, 2), 5); assertEquals(divide(5, 2), 2.5); }); Deno.test("divide throws error on zero", () => { assertThrows( () => divide(10, 0), Error, "Division by zero" ); });

异步测试

typescript
Deno.test("async function", async () => { const data = await fetchData(); assertEquals(data.length, 10); }); Deno.test("timeout test", async () => { const result = await slowOperation(); assertEquals(result, "done"); }, { timeout: 5000 });

测试钩子

typescript
Deno.test("with setup and teardown", { sanitizeOps: false, sanitizeResources: false, fn: async () => { // Setup const db = await connectDatabase(); try { // Test const user = await db.createUser({ name: "John" }); assertEquals(user.name, "John"); } finally { // Teardown await db.close(); } } });

编译为可执行文件 (deno compile)

基本用法

bash
# 编译为可执行文件 deno compile src/main.ts # 指定输出文件名 deno compile --output=myapp src/main.ts # 指定目标平台 deno compile --target=x86_64-unknown-linux-gnu src/main.ts # 包含权限 deno compile --allow-net --allow-read src/main.ts

示例

typescript
// cli.ts #!/usr/bin/env -S deno run const name = Deno.args[0] || "World"; console.log(`Hello, ${name}!`);

编译:

bash
deno compile --output=hello cli.ts ./hello Deno # 输出: Hello, Deno!

打包 (deno bundle)

基本用法

bash
# 打包为单个文件 deno bundle src/main.ts bundle.js # 指定输出文件 deno bundle src/main.ts dist/app.bundle.js # 指定源映射 deno bundle --source-map=inline src/main.ts bundle.js

示例

typescript
// main.ts import { greet } from "./greet.ts"; import { farewell } from "./farewell.ts"; console.log(greet("Deno")); console.log(farewell("Deno"));

打包:

bash
deno bundle main.ts app.bundle.js

文档生成 (deno doc)

基本用法

bash
# 生成文档 deno doc src/main.ts # 生成 HTML 文档 deno doc --html src/main.ts # 查看特定符号的文档 deno doc src/main.ts MyFunction # 生成 JSON 文档 deno doc --json src/main.ts

编写文档

typescript
/** * 计算两个数的和 * * @param a - 第一个数 * @param b - 第二个数 * @returns 两个数的和 * * @example * ```ts * add(1, 2); // 返回 3 * ``` */ export function add(a: number, b: number): number { return a + b; } /** * 用户接口 */ export interface User { /** 用户 ID */ id: number; /** 用户名 */ name: string; /** 用户邮箱 */ email: string; }

性能基准测试 (deno bench)

基本用法

bash
# 运行基准测试 deno bench # 运行指定文件 deno bench src/bench.ts

编写基准测试

typescript
import { bench, runBenchmarks } from "https://deno.land/std@0.208.0/testing/bench.ts"; bench("for loop", () => { let sum = 0; for (let i = 0; i < 1000; i++) { sum += i; } }); bench("reduce", () => { const arr = Array.from({ length: 1000 }, (_, i) => i); arr.reduce((sum, num) => sum + num, 0); }); await runBenchmarks();

配置文件

使用 deno.jsondeno.jsonc 统一配置:

json
{ "compilerOptions": { "strict": true }, "lint": { "files": { "include": ["src/"], "exclude": ["src/test/"] }, "rules": { "tags": ["recommended"], "exclude": ["no-unused-vars"] } }, "fmt": { "files": { "include": ["src/"], "exclude": ["dist/"] }, "options": { "useTabs": false, "lineWidth": 100, "indentWidth": 2, "singleQuote": true, "proseWrap": "preserve" } }, "tasks": { "dev": "deno run --watch src/main.ts", "test": "deno test --allow-net", "build": "deno compile src/main.ts" } }

任务运行

Deno 支持定义和运行任务:

bash
# 列出所有任务 deno task # 运行特定任务 deno task dev # 运行测试任务 deno task test

最佳实践

  1. 使用配置文件:在 deno.json 中统一配置所有工具
  2. 自动化检查:在 CI/CD 中集成 lint 和 test
  3. 保持一致性:使用 fmt 确保代码风格统一
  4. 编写测试:为关键功能编写测试
  5. 文档化代码:使用 JSDoc 注释生成文档
  6. 性能优化:使用 bench 识别性能瓶颈

Deno 的内置工具链提供了完整的开发体验,无需安装额外的依赖,大大简化了项目配置和维护工作。

标签:Deno