# @applifting-io/nestjs-decorated-config 中文文档

规范地址：https://npmcn.com/package/%40applifting-io/nestjs-decorated-config/

版本：1\.0\.8
npm 元数据更新时间：2025-03-29T09:23:02.085Z
中文译文更新时间：2026-11-06T11:44:39.983Z
软件包许可：ISC

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

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

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

- 包体积（解压后）：22.2 kB，19 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：@nestjs/common \>=8\.0\.0，class-validator \>=0\.14\.0，reflect-metadata \>=0\.1\.13
- 首次发布：2023-10-25T13:09:25.821Z
- 最新版本发布：2025-03-29T09:23:01.892Z
- 近 30 天下载量：10218（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 0 个）

## 中文简介

Nest.js 配置模块,并使用类验证器装饰器进行校验

## 安装

```sh
npm install @applifting-io/nestjs-decorated-config
```

也可以使用：`pnpm add @applifting-io/nestjs-decorated-config`、`yarn add @applifting-io/nestjs-decorated-config`、`bun add @applifting-io/nestjs-decorated-config`

## README

# NestJS 装饰配置

## 说明

环境变量配置模块 [(原始内容存档于2019-09-21) (英语). Nest.js](https://github.com/nestjs/nest) 使用 [类验证器](https://github.com/typestack/class-validator) 作装饰.

## 安装

```bash
$ npm i @applifting-io/nestjs-decorated-config
```

## 使用量

假设您有以下 .env 文件( 或者在提供这些变量的环境中启动您的应用程序)

```.env
SECRET="WmOZI77oOQf76cM9GASDWB7tS3MZ01TPM395FCUN9oE="
URL="http://localhost:3000"
```

### 配置服务定义

创建自己的配置服务 。 为每个环境变量定义属性。 用 @ Env 装饰器装饰它们 - 确保第一个参数符合您的环境变量名称 .

可选地用类验证器装饰您的属性.

```ts
// config.service.ts
import { Env } from '@applifting-io/nestjs-decorated-config';
import { Injectable } from '@nestjs/common';
import { IsNotEmpty, IsUrl } from 'class-validator';

@Injectable()
export class ConfigService {
  @Env('URL')
  @IsUrl()
  readonly url: string;

  @Env('SECRET')
  @IsNotEmpty()
  readonly secret: string;

  @Env('BOOLEAN_VAR', {
    defaultValue: true, // will use true if no other value is populated from environment
  })
  readonly booleanVar: boolean;

  @Env('ARRAY_VAR', {
    delimiter: '|', // will use comma as a delimiter for the array ("," is the default delimiter)
    parseArray: true, // will parse the array from string to array of strings
  })
  readonly arrayVar: string[];

  @Env('NUMBER_VAR', {
    defaultValue: 42, // will use 42 if no other value is populated from environment
  })
  readonly numberVar: number;

  @Env('JSON_VAR', {
    parseJson: true, // will parse stringified JSON object
  })
  readonly jsonVar: {
    key: string;
  };

  @Env('EXPOSED_VAR', {
    expose: true, // will print the value of this variable in the console on startup
  })
  readonly exposedVar: string;
}
```

#### 选项

@ Env 选择预期 `EnvDecoratorOptions` 作为第二个参数:

```ts
type EnvDecoratorOptions<T = any> = {
  /**
   * Variable's default value, used if no other value is populated from environment. Undefined by default
   */
  defaultValue?: T | (() => T);

  /**
   * Exposing will show the value of variable in log. False by default
   */
  expose?: boolean;

  /**
   * Removes last string character, if it is a forward slash. False by default
   */
  removeTrailingSlash?: boolean;

  /**
   * Parses the value to a JavaScript object with JSON.parse. Throws on invalid input. False by default
   */
  parseJson?: boolean;
};
```

### 配置模块初始化

导入并添加 CfigMudule 到导入您的根模块的数组 .

```ts
// app.module.ts
import { ConfigModule } from '@applifting-io/nestjs-decorated-config';
import { Module } from '@nestjs/common';
import { ConfigService } from 'config.service.ts';

@Module({
  imports: [ConfigModule.forRootAsync(ConfigService)],
})
export class AppModule {}
```

#### 选项

CfigMudule. for RootAsync 可选预期 `ConfigModuleOptions` 作为第二个参数:

```ts
type ConfigModuleOptions = {
  /**
   * Print all variables with `expose: true`. False by default
   */
  printOnStartup?: boolean;
  /**
   * Validate all variables using class-validator decorators. True by default
   */
  validate?: boolean;
};
```

### 需要时注入配置

全球都有配置服务,像其他供应商一样注入

```ts
// example.service.ts

@Injectable()
export class ExampleService {
  constructor(private readonly config: ConfigService) {}

  example() {
    console.log(config.url); // => 'http://localhost:3000'
    console.log(config.secret); // => 'WmOZI77oOQf76cM9GASDWB7tS3MZ01TPM395FCUN9oE='
    console.log(config.booleanVar); // => true
    console.log(config.arrayVar); // => ['value1', 'value2']
    console.log(config.numberVar); // => 42
    console.log(config.jsonVar); // => { key: 'value' }
    console.log(config.exposedVar); // => 'value'
  }
}
```

## 重要

> **重要性** 如果使用.env文件 : `Env` 装饰者从 `process.env`。由于 TS 中装饰器的性质,您需要确保从.env 文件装入变量 **在此之前** 导入 `Env` 或本身进口的任何其他联署材料模块 `Env`。 。 。 .

在实践中实现这一点的一个方法是运行 Dotenv , 然后在主.ts 切入点中动态导入您的其余应用程序

```ts
// main.ts
import * as dotenv from 'dotenv';

// Dotenv needs to run before importing bootstrap, because @Env decorators are
// executed when JS interpreter interprets the decorated class which is in
// bootstrap's import tree, and we need env var resolution to be finished before that
dotenv.config();

import('./bootstrap').then(({ bootstrap }) => bootstrap());
```

## 常见问题

### @applifting-io/nestjs-decorated-config 是什么？

Nest\.js 配置模块,并使用类验证器装饰器进行校验

### 如何安装 @applifting-io/nestjs-decorated-config？

在项目目录运行 npm install @applifting-io/nestjs-decorated-config，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@nestjs/common（\>=8\.0\.0）、class-validator（\>=0\.14\.0）、reflect-metadata（\>=0\.1\.13）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @applifting-io/nestjs-decorated-config 支持 TypeScript 吗？

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

### @applifting-io/nestjs-decorated-config 支持 ESM 还是 CommonJS？

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

### @applifting-io/nestjs-decorated-config 可以商用吗？

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

### @applifting-io/nestjs-decorated-config 的下载量有多少？

根据 npm 官方下载统计，@applifting-io/nestjs-decorated-config 在 2026/10/07 – 2026/11/05 这 30 天内被下载 10,218 次，日均约 341 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @applifting-io/nestjs-decorated-config 还在维护吗？

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

