
# 功能

> 启用并配置 Nitro 的内置能力，例如 OpenAPI、插件、模块和任务。

::note
本页所有示例都假设已在 `nitro.config.ts` 中导入以下内容：

```ts
import { defineConfig } from "nitro";
```
::

### `features`

- 默认值：`{}`{lang=ts}

启用内置功能。

#### `runtimeHooks`

- 默认值：自动检测（至少存在一个 Nitro 插件时启用）

启用请求和响应的运行时钩子。

#### `websocket`

- 默认值：`false`{lang=ts}

启用 WebSocket 支持。

:read-more{to="/docs/websocket"}

#### `fastResponse`

- 默认值：启用 [`node`](/config/build#node) 时为 `true`{lang=ts}，否则为 `false`{lang=ts}

将全局 `Response` 替换为 srvx 的 `FastResponse`，使处理器中的 `new Response()` 在 Node.js 下跳过原生 `Response` 的开销。原生和快速响应都可以正常使用 `instanceof Response` 判断。

在没有 `FastResponse` 实现的运行时（Bun、Deno 和 Workers）中无效。

::note
`FastResponse` 会延迟读取响应体和响应头，并跳过部分构造函数校验。例如，在 Node.js 中 `new Response("body", { status: 204 })` 不会抛出错误，而在其他运行时会。设置 `fastResponse: false` 可改用原生 `Response`。
::

```ts
export default defineConfig({
  features: {
    runtimeHooks: true,
    websocket: true, // enable WebSocket support
    fastResponse: false, // use the native global Response
  },
});
```

### `experimental`

- 默认值：`{}`{lang=ts}

启用实验性功能。

#### `openAPI`

- 默认值：`false`{lang=ts}

启用 `/_scalar`、`/_swagger` 和 `/_openapi.json` 端点。

::note
建议优先使用顶层 [`openAPI`](#openapi) 选项进行配置。
::

#### `typescriptBundlerResolution`

启用 TypeScript 打包器模块解析。参见 [TypeScript#51669](https://github.com/microsoft/TypeScript/pull/51669)。

::note
此标志目前不起作用：`nitro/tsconfig` 和生成的 tsconfig 始终使用打包器模块解析。
::

#### `asyncContext`

为 `useRequest()` 启用原生异步上下文支持。

#### `sourcemapMinify`

设为 `false` 可禁用实验性的 source map 压缩（启用 `sourcemap` 时默认开启）。

#### `entriesAwareLibChunks`

设为 `false` 可禁用按入口拆分的库分块（Rolldown 和 Vite 构建器）。

默认情况下，每个 `node_modules` 包的分块会按使用它的入口（主入口和延迟加载的路由处理器）拆分，因此启动时不会加载仅供延迟路由使用的代码。由许多小模块组成的包可能被拆分成许多小分块。禁用此选项会生成数量更少、体积更大的库分块。

#### `envExpansion`

允许在运行时配置中展开环境变量。参见[配置指南](/docs/configuration#env-expansion)和 [#2043](https://github.com/nitrojs/nitro/pull/2043)。

#### `database`

启用实验性的数据库支持。参见[数据库](/docs/database)。

#### `tasks`

启用实验性的任务支持。参见[任务](/docs/tasks)。

#### `tracingLogger`

使用内置且无依赖的遥测接收器，将 Nitro 追踪通道的 span 输出到控制台；每个已完成的 span（h3、srvx、unstorage、db0 等）都会记录下来。需要启用 [`tracingChannel`](/config/advanced#tracingchannel)。

```ts
export default defineConfig({
  experimental: {
    typescriptBundlerResolution: true,
    asyncContext: true,
    envExpansion: true,
    database: true,
    tasks: true,
  },
});
```

### `openAPI`

顶层 OpenAPI 配置。

可以传入对象来修改 OpenAPI 规范：

```js
openAPI: {
  meta: {
    title: 'My Awesome Project',
    description: 'This might become the next big thing.',
    version: '1.0'
  }
}
```

这些路由在生产环境中默认禁用。若要启用，请使用 `production` 键。
`"runtime"` 支持使用中间件；`"prerender"` 效率最高，因为 JSON 响应是固定的。

```js
openAPI: {
    // IMPORTANT: make sure to protect OpenAPI routes if necessary!
    production: "runtime", // or "prerender"
}
```

若要自定义 Scalar 集成，可以像下面这样[传入配置对象](https://github.com/scalar/scalar)：

```js
openAPI: {
  ui: {
    scalar: {
      theme: 'purple'
    }
  }
}
```

若要自定义 Swagger UI，可以传入任意 [Swagger UI 配置选项](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/)：

```js
openAPI: {
  ui: {
    swagger: {
      persistAuthorization: true,
      deepLinking: true,
      docExpansion: 'none',
      filter: true,
    }
  }
}
```

自定义端点：

```js
openAPI: {
  route: "/_docs/openapi.json",
  ui: {
    scalar: {
      route: "/_docs/scalar"
    },
    swagger: {
      route: "/_docs/swagger"
    }
  }
}
```

:read-more{to="/docs/openapi"}

### `renderer`

- 类型：`false`{lang=ts} | `{ handler?: string, static?: boolean, template?: string }`{lang=ts}

指向主渲染入口（文件应将事件处理器作为默认导出）。

```ts
export default defineConfig({
  renderer: {
    handler: "~/renderer", // path to the render handler
  },
});
```

:read-more{to="/docs/renderer"}

### `ssrRoutes`

需要进行服务端渲染的路由。

```ts
export default defineConfig({
  ssrRoutes: ["/app/**"],
});
```

### `modules`

- 默认值：`[]`{lang=ts}

Nitro 模块数组。模块可以是字符串（路径）、带有 `setup` 函数的模块对象或函数。

```ts
export default defineConfig({
  modules: [
    "./modules/my-module.ts",
    (nitro) => {
      nitro.hooks.hook("compiled", () => { /* ... */ });
    },
  ],
});
```

### `plugins`

- 默认值：`[]`{lang=ts}

Nitro 插件路径数组。首次初始化时会按顺序执行这些插件。

注意，Nitro 会自动注册 `plugins/` 目录中的插件。

```ts
export default defineConfig({
  plugins: [
    "~/plugins/my-plugin.ts",
  ],
});
```

:read-more{to="/docs/plugins"}

### `tasks`

- 默认值：`{}`{lang=ts}

任务定义。每个键都是任务名称，并可选包含 `handler` 路径和 `description`。

从 `<serverDir>/tasks/` 扫描到的任务只需在此处设置 `description`。`handler` 会按原样导入，不会相对于项目根目录解析，因此必须是绝对路径或包名。

```ts
import { fileURLToPath } from "node:url";

export default defineConfig({
  tasks: {
    "db:migrate": {
      description: "Run database migrations",
    },
    "db:seed": {
      handler: fileURLToPath(new URL("scripts/seed.ts", import.meta.url)),
      description: "Seed the database",
    },
  },
});
```

:read-more{to="/docs/tasks"}

### `scheduledTasks`

- 默认值：`{}`{lang=ts}

Cron 表达式到任务名称的映射。

```ts
export default defineConfig({
  scheduledTasks: {
    "0 * * * *": "cleanup:temp",
    "*/5 * * * *": ["health:check", "metrics:collect"],
  },
});
```

:read-more{to="/docs/tasks"}

### `scheduler`

- 默认值：`{}`{lang=ts}

运行 `scheduledTasks` 的选项。

- `runner`（默认值：`true``）：使用内置 Cron 运行器在进程内运行 `scheduledTasks`。适用于 `dev`、`node_*`、`bun` 和 `deno_server` 预设。

由其他机制（例如系统 Cron）触发定时任务时，请设置 `runner: false`。任务仍会保持注册，因此 `runCronTasks()` 和 `/_nitro/tasks` 开发路由仍可使用。平台定时任务（Cloudflare Cron Triggers、Vercel Cron Jobs）不受影响。

```ts
export default defineConfig({
  scheduler: { runner: false },
});
```

### `virtual`

- 默认值：`{}`{lang=ts}

动态虚拟导入名称到其内容的映射，也可以映射到返回内容的（异步）函数。

```ts
export default defineConfig({
  virtual: {
    "#config": `export default { version: "1.0.0" }`,
  },
});
```

### `wasm`

- 类型：`false`{lang=ts} | `UnwasmPluginOptions`{lang=ts}
- 默认值：`{}`{lang=ts}

WASM 支持配置。可用选项参见 [unwasm](https://github.com/unjs/unwasm)。

```ts
export default defineConfig({
  wasm: {}, // enable WASM import support
});
```
