在Nest.js中定义节点环境 [英] Defining Node environment in Nest.js
问题描述
我正在设置Nest.js项目,我正在寻找定义Node环境的有效解决方案,ConfigService
使用它来加载环境变量:
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 {}
现在我直接在npm脚本中定义它(例如"start:dev": "NODE_ENV=development nodemon"
),但是我想知道是否有更好的方法来处理不同的环境,而不是将其附加在每个脚本中?
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?
推荐答案
开发
如果应始终为development
,只需将其设置为系统变量,请参见下面的生产/登台.如果要在开发过程中运行不同的环境,则可以添加npm运行脚本.此外,您可以使用 cross-env
来确保您的脚本可以在不同的平台上运行:
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",
测试
如果要在其他环境中运行集成测试,则可以在jest-e2e.json
中进行设置:
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.
这篇关于在Nest.js中定义节点环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!