--- tags: nestjs --- # 用更簡單的方式處理NestJS設定檔:介紹 `nest-simple-config` 在 NestJS 中,設定管理是一項基礎但關鍵的工作。 NestJS 官方提供 `@nestjs/config`,支援 `.env` 檔讀取與基本類型驗證。若搭配 `Joi` 或 `registerAs()`,也可達到較高程度的結構與驗證控制。不過在開發實務中,如果你偏好 `ASP.NET Core` 那種透過 `IOptions<T>` 強型別設定物件進行注入的風格,NestJS 並沒有直接對應的設計。 `nest-simple-config` 則提供了一個更直覺的方式,讓設定管理具備以下特色: - 類別即為設定結構,支援巢狀與驗證 - 支援 JSON/YAML/ENV 混合設定來源,自動合併 - 支援 `@InjectConfig()` + `Options<T>` 注入方式 - 類似 `ASP.NET Core` 的 `IOptions<T>` 使用體驗 --- ## 適合使用 `nest-simple-config` 的情境 - 偏好使用強型別 `class` 定義設定資料 - 想在應用啟動時就驗證設定格式 - 設定檔案支援 JSON、YAML,以及結構化環境變數 ENV --- ## `nest-simple-config` 套件安裝 ```shell=bash npm i --save nest-simple-config ``` --- ## 🛠 快速使用範例 ### 設定檔(`appsettings.json`) ```json { "database": { "host": "localhost", "port": 3306 } } ``` ### 設定類別(`database-options.ts`) ```ts import { IsString, IsInt } from 'class-validator'; import { BindOption } from '@mediaedge4tw/nest-simple-config'; @BindOption('database') export class DatabaseOptions { @IsString() host!: string; @IsInt() port!: number; } ``` ### 模組註冊 ```ts SimpleConfigModule.forRoot({ configFileOptions: { filename: 'appsettings.json' }, }), SimpleConfigModule.registerOptions([DatabaseOptions]) ``` ### 注入使用 ```ts @Injectable() export class MyService { constructor( @InjectConfig(DatabaseOptions) private readonly db: Options<DatabaseOptions>, ) { console.log(db.value.host); // 已驗證、具型別安全 } } ``` --- ## 🧩 不使用 Option 類別時的簡易方式 若不想定義設定類別,也可以直接注入 `Configuration`,並透過 `.get<T>()` 取得設定值: ```ts type DatabaseConfig = { host: string; port: number; }; @Injectable() export class SimpleService { constructor(private readonly config: Configuration) { const databaseConfig = this.config.get<DatabaseConfig>('database'); console.log(`Database port is ${databaseConfig.port}`); } } ``` 這種方式類似 `@nestjs/config` 的 `ConfigService.get()`,但資料來源來自經過 `nest-simple-config` 合併處理的 JSON/YAML/ENV 設定內容,仍保有一致性與覆寫邏輯。 --- ## 🔁 功能差異與對照:`@nestjs/config` vs `nest-simple-config` | 能力 | `@nestjs/config` | `nest-simple-config` | |------|------------------|-----------------------| | ✅ 設定類別綁定 | ✅ 使用泛型 (`ConfigType<typeof x>`) 搭配 `registerAs()` | ✅ 使用 `@BindOption()` 裝飾器,設定類別即為可被 Option 注入型別 | | ✅ 啟動時驗證 | ✅ 支援 Joi schema 或自訂 `validate()` 處理 | ✅ 使用 `class-validator` 驗證類別屬性,失敗即阻止啟動 | | ✅ 巢狀結構支援 | ✅ 需手動撰寫 config factory 並明確轉型 | ✅ 自動處理巢狀結構並轉換為設定類別 | | ✅ 多來源合併 | 🔶 須自行設計 `.env` / YAML / registerAs 的合併流程 | ✅ 預設依來源優先順序合併設定(JSON/YAML → ENV),也可透過 provider builder 自訂策略 | | ✅ 設定 DI 模式 | 🔶 使用 `ConfigService.get()` + dot notation | ✅ 支援 `@InjectConfig()` 直接注入 `Options<T>`,模擬 `ASP.NET Core` `IOptions<T>`,也支援直接注入 `Configuration.get()` 方式 | --- ## ✨ 小結 `@nestjs/config` 功能非常完整,透過手動組合也能實現型別與驗證支援。但若你想要: - 快速建立巢狀設定類別 - 使用類別注入與自動驗證 - 不必手動撰寫轉換與錯誤處理邏輯 那麼 `nest-simple-config` 會是更簡潔的選擇。 --- ## 📦 套件資訊 - GitHub: https://github.com/cymondez/nest-simple-config - NPM: https://www.npmjs.com/package/@mediaedge4tw/nest-simple-config - 最新版本:`2.0.0` (2025-07-12) - 授權:MIT - 相容版本:NestJS 9 ~ 11+ --- ## 📌 延伸參考 - [NestJS 官方 ConfigModule 說明](https://docs.nestjs.com/techniques/configuration) - [class-validator](https://github.com/typestack/class-validator) --- > 有任何意見或建議,歡迎開 [Issue](https://github.com/cymondez/nest-simple-config/issues) 或 PR 一起參與改善!