[英]Defining Node environment in Nest.js
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:我正在设置 Nest.js 项目,我正在寻找定义 Node 环境的有效解决方案,
ConfigService
使用它来加载环境变量:
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?现在我直接在 npm 脚本中定义它(例如
"start:dev": "NODE_ENV=development nodemon"
),但我想知道是否有更好的方法来处理不同的环境而不是将它附加到每个脚本?
If it should be always development
just set it as a system variable, see Production / Staging below.如果它应该始终是
development
只需将其设置为系统变量,请参阅下面的生产/暂存。 If you want to run different environments during development, appending your npm run scripts is the way to go.如果你想在开发过程中运行不同的环境,附加你的 npm run 脚本是一种方法。 Additionally, you can use
cross-env
to ensure that your scripts work on different platforms:此外,您可以使用
cross-env
来确保您的脚本在不同平台上工作:
"start": "cross-env NODE_ENV=development ts-node -r tsconfig-paths/register src/main.ts",
If you want to run your integration tests in a different environment, you can set it in your jest-e2e.json
:如果你想在不同的环境中运行你的集成测试,你可以在
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);
On a staging or production system, I'd recommend setting it as a normal system variable, see this thread .在登台或生产系统上,我建议将其设置为普通系统变量,请参阅此线程。
没有跨环境,你可以使用:
"start:local": "NODE_ENV=test ts-node -r tsconfig-paths/register src/main.ts "
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.