# @fastify/env 中文文档

规范地址：https://npmcn.com/package/%40fastify/env/

版本：7\.0\.1
npm 元数据更新时间：2026-10-18T12:30:31.656Z
中文译文更新时间：2026-11-14T11:18:02.470Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fastify/env
原文对照：https://npmcn.com/package/%40fastify/env/?lang=original
项目主页：https://github.com/fastify/fastify-env#readme
源码仓库：https://github.com/fastify/fastify-env

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：21.5 kB，14 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2022-04-27T13:48:31.417Z
- 最新版本发布：2026-10-09T14:38:24.215Z
- 近 30 天下载量：940305（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：15（近 12 个月 3 个）

## 中文简介

快速检查环境变量的插件

## 安装

```sh
npm install @fastify/env
```

也可以使用：`pnpm add @fastify/env`、`yarn add @fastify/env`、`bun add @fastify/env`

## README

# @ fastify/env (法语)

[![CI](https://github.com/fastify/fastify-env/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-env/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/env.svg?style=flat)](https://www.npmjs.com/package/@fastify/env) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

快速检查环境变量的插件

## 安装

```
npm i @fastify/env
```

### 兼容性

| 插件版本 | 快速化版本 |
| --- | --- |
| `>=5.x` | `^5.x` |
| `^4.x` | `^4.x` |
| `>=2.x <4.x` | `^3.x` |
| `>=0.x 2.x` | `^2.x` |
| `>=0.x 2.x` | `^1.x` |

请注意,如果一个快取版本没有支持,那么该插件的相应版本也一样 上表列出. 见 [快速化 LTS 政策](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) 更多细节.

## 使用量

```js
const fastify = require('fastify')()
const fastifyEnv = require('@fastify/env')

const schema = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'string',
      default: 3000
    }
  }
}

const options = {
  confKey: 'config', // optional, default: 'config'
  schema: schema,
  data: data // optional, default: process.env
}

fastify
  .register(fastifyEnv, options)
  .ready((err) => {
    if (err) console.error(err)

    console.log(fastify.config) // or fastify[options.confKey]
    console.log(fastify.getEnvs())
    // output: { PORT: 3000 }
  })
```

您也可以使用此函数 `getEnvs()` 从处理器函数内获取的请求:

```js
fastify.get('/', (request, reply) => {
    console.log(request.getEnvs())
    // output: { PORT: 3000 }
})
```

注意 `getEnvs` 如果装饰已经存在, 则不会添加装饰 .

此模块是一个包装器周围 [环境图](https://www.npmjs.com/package/env-schema)。 。 。 . 读一个 `.env` 您必须设置的文件 `dotenv` 选项中:

```js
const options = {
  dotenv: true // will read .env in root folder
}

// or, pass config options supported by env-schema
const options = {
  dotenv: {
    path: `${__dirname}/.env`,
    encoding: 'utf8'
  }
}

```

### 格式和自定义 Ajv 选项

`@fastify/env` 以其 **拥有 Ajv 实例** (以千美元计) [环境图](https://www.npmjs.com/package/env-schema)),独立于路线的快用. 在快捷实例上配置的格式或选项( E)`Fastify({ ajv: ... })`),或来自类型提供者,如TypeBox,是 **没有** 应用到环境图中,所以使用 `format` 关键词结果如下:

```
unknown format "uuid" ignored in schema at path "#/properties/ID"
```

用插件的 Ajv 实例注册格式 `ajv.customOptions` 选项,它可以是 Ajv 选项对象,也可以是接收并返回 Ajv 实例的函数. 用于标准格式 [ajv 格式](https://www.npmjs.com/package/ajv-formats) (单位:千美元)`npm i ajv-formats`,它不是此插件的依赖性 :

```js
await fastify.register(fastifyEnv, {
  schema: {
    type: 'object',
    required: ['ID'],
    properties: {
      ID: { type: 'string', format: 'uuid' }
    }
  },
  ajv: {
    customOptions (ajvInstance) {
      require('ajv-formats')(ajvInstance)
      // or: ajvInstance.addFormat('myFormat', (value) => /* ... */)
      return ajvInstance
    }
  }
})
```

与 TypeBox (1.x,即:. `@fastify/type-provider-typebox` QQ 6 您可以再使用 TypeBox 中包含的格式 :

```ts
import { Format, Type } from '@fastify/type-provider-typebox'

await fastify.register(fastifyEnv, {
  schema: Type.Object({
    ID: Type.String({ format: 'uuid' })
  }),
  ajv: {
    customOptions (ajvInstance) {
      for (const entry of Format.Entries()) {
        ajvInstance.addFormat(...entry)
      }
      // Or if you only want to register a specific format:
      // ajvInstance.addFormat('uuid', Format.Get('uuid'))
      return ajvInstance
    }
  }
})
```

见 [env-sema 文档](https://github.com/fastify/env-schema#readme) 所有支持的 Ajv 选项.

### 使用 @ fastify/ env 配置其他插件

这个 `@fastify/env` 插件同步加载。 如果您想要在启动序列前在不同的插件中使用其值,则需要确保:

1.  `@fastify/env` 首先登记.
2.  等待插件注册或等待后 ()

```js
await fastify.register(fastifyEnv)
// fastify.config can be used in here
```

或

```js
fastify.register(fastifyEnv)
await fastify
// fastify.config can be used in here
```

**编号** 用于此插件的额外属性支持已禁用, 其间 `additionalProperties` 设置为 `false` 内部.

### 字体

要输入封存实例,请:

-   使用该 `declaration merging` 技术,加强 `FastifyInstance` 在选项中定义的属性及其密钥类型 :

```typescript
declare module 'fastify' {
  interface FastifyInstance {
    config: { // this should be the same as the confKey in options
      // specify your typing here
      FOO: string
    };
  }
}

const fastify = Fastify()
fastify.register(fastifyEnv)

fastify.config.FOO // will be a string
fastify.config.BAR // error: Property BAR does not exist on type { FOO: string }
```

-   使用通用函数 `getEnvs()` 以获取已输入的对象 :

```typescript
type Envs = {
  FOO: string
}

const fastify = Fastify()
await fastify.register(fastifyEnv)

const envs = fastify.getEnvs<Envs>() // envs will be of type Envs

envs.FOO // will be a string
envs.BAR // error: Property BAR does not exist on type Envs
```

如果是这样,建议使用 [json-schema-to-ts (日语)](https://github.com/ThomasAribart/json-schema-to-ts) 使该类型始终与实际计划同步.

## 承认

请赞助人: [米娅平台](https://mia-platform.eu/)。 。 。 .

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/env/LICENSE)。 。 。 .

## 常见问题

### @fastify/env 是什么？

快速检查环境变量的插件

### 如何安装 @fastify/env？

在项目目录运行 npm install @fastify/env，或使用 pnpm add / yarn add / bun add。

### @fastify/env 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @fastify/env 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fastify/env 可以商用吗？

@fastify/env 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fastify/env 的下载量有多少？

根据 npm 官方下载统计，@fastify/env 在 2026/10/15 – 2026/11/13 这 30 天内被下载 940,305 次，日均约 31,344 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fastify/env 还在维护吗？

最新版本 7\.0\.1 发布于 2026/10/09（1 个月前）；至今共发布 15 个版本，其中过去 12 个月发布了 3 个；首次发布于 2022/04/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

