Home 在 nest 中使用设置环境变量
Post
Cancel

在 nest 中使用设置环境变量

1. 安装 @nestjs/config

1
npm i --save @nestjs/config

2. 创建环境变量文件

1
touch .env .env.development .env.production

3. 根模块中注入

1
2
3
4
5
6
7
8
9
10
11
12
import { Module } from '@nestjs/common';
    import { ConfigModule } from '@nestjs/config';

    @Module({
        imports: [
            ConfigModule.forRoot({
                envFilePath: ['.env', `.env.${process.env.NODE_ENV}`],
            })
        ],
    })
    export class AppModule {}`
}

4. 编写环境变量

.env 共用变量

.env.development 开发环境下使用

.env.production 生产环境下使用

package.json 下的 scripts 中,添加判断环境变量。

1
2
3
{
    "scripts": "NODE_ENV=development npm start"
}

在项目中使用

1
process.env.[VAR]" />

说明

通过在 scripts 中注入一个变量,来判断项目要加载哪个环境变量文件

参考地址

Nest @nestjs/config
dotenv

This post is licensed under CC BY 4.0 by the author.
Recently Updated
Trending Tags
Contents

-

-

Trending Tags