Defining Node environment in Nest.js

两盒软妹~` 提交于 2020-01-02 17:12:30

问题


I'm in the process of setting up Nest.js project and I look for the efficient solution of defining Node environment which is used by the ConfigService for loading environment variables:

import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({
    providers: [
        {
            provide: ConfigService,
            useValue: new ConfigService(`environments/${process.env.NODE_ENV}.env`)
        }
    ],
    exports: [ConfigService]
})
export class ConfigModule {}

Right now I'm defining it directly in the npm scripts (for example "start:dev": "NODE_ENV=development nodemon"), but I'm wondering if there is some better approach for handling different environments instead of appending it in every script?


回答1:


Development

If it should be always development just set it as a system variable, see Production / Staging below. If you want to run different environments during development, appending your npm run scripts is the way to go. Additionally, you can use cross-env to ensure that your scripts work on different platforms:

"start": "cross-env NODE_ENV=development ts-node -r tsconfig-paths/register src/main.ts",

Testing

If you want to run your integration tests in a different environment, you can set it in your jest-e2e.json:

"globals": {
  "NODE_ENV": "test"
}

Setting (or changing) your environment for one particular test can also be done in the test code:

let previousNodeEnv;
beforeAll(() => {
  previousNodeEnv = process.env.NODE_ENV;
  process.env.NODE_ENV = 'test';
});

afterAll(() => process.env.NODE_ENV = previousNodeEnv);

Production / Staging

On a staging or production system, I'd recommend setting it as a normal system variable, see this thread.



来源:https://stackoverflow.com/questions/55092953/defining-node-environment-in-nest-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!