@applifting-io/nestjs-decorated-config

中文文档
1.0.8发布于 2025/03/29ISCTypeScriptCommonJS零依赖近 30 天下载 1万

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

中文使用文档
文档目录7 节
  1. 说明
  2. 安装
  3. 使用量
  4. 配置服务定义
  5. 配置模块初始化
  6. 需要时注入配置
  7. 重要

NestJS 装饰配置

说明

环境变量配置模块 (原始内容存档于2019-09-21) (英语). Nest.js 使用 类验证器 作装饰.

安装

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

使用量

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

SECRET="WmOZI77oOQf76cM9GASDWB7tS3MZ01TPM395FCUN9oE="
URL="http://localhost:3000"

配置服务定义

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

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

// 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 作为第二个参数:

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 到导入您的根模块的数组 .

// 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 作为第二个参数:

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;
};

需要时注入配置

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

// 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 切入点中动态导入您的其余应用程序

// 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 共发布 9 个版本,首次发布于 2023/10/25;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.8latest2025/03/291.6 年前
1.0.72025/03/231.6 年前
1.0.62025/03/231.6 年前
1.0.52025/03/231.6 年前
1.0.42024/07/182 年前
1.0.32024/07/182 年前

关于 @applifting-io/nestjs-decorated-config 的常见问题

@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 和提交记录判断。