问题
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