@applifting-io/nestjs-decorated-config

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

Nest.js config module with validation using class-validator decorators

原始使用文档
文档目录7 节
  1. Description
  2. Installation
  3. Usage
  4. ConfigService definition
  5. ConfigModule initialization
  6. Inject ConfigService where needed
  7. Important

NestJS Decorated Config

Description

Environment variable configuration module for Nest.js featuring validation using class-validator decorators.

Installation

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

Usage

Let's say you have the following .env file (or start your application in an environment providing those variables)

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

ConfigService definition

Create your own ConfigService. Define a property for each environment variable. Decorate them with @Env decorator - make sure the first parameter matches your environment variable name.

Optionally decorate your properties with class-validator decorators.

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

Options

@Env optionally expects EnvDecoratorOptions as second parameter:

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

ConfigModule initialization

Import and add ConfigModule to imports array of your root module.

// 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 {}

Options

ConfigModule.forRootAsync optionally expects ConfigModuleOptions as second parameter:

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

Inject ConfigService where needed

ConfigService is available globally, inject it like any other provider

// 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'
  }
}

Important

IMPORTANT If using .env files: Env decorators read environment variable values from process.env. Due to the nature of decorators in TS, you need to make sure variables from .env file are loaded into process.env before importing Env or any other JS module that itself imports Env.

One way to achieve this in practice is to run dotenv and then dynamically import the rest of your application in your main.ts entrypoint

// 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 config module with validation using class-validator decorators

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