2.1.2 • Published 1 year ago

nestjs-env v2.1.2

Weekly downloads
8
License
MIT
Repository
github
Last release
1 year ago

Install

Yarn

yarn add nestjs-env

NPM

npm install nestjs-env --save

This library is not responsible for loading environment variables from a file, for this you need to use env-cmd or dotenv.

Getting Started

Let's imagine that we have a folder called src/config in our project that contains several configuration files.

/src
├── app.module.ts
├── app.service.ts
├── config
│   ├── app.config.ts
│   └── index.ts
bootstrap.ts

Example app.config.ts

import { Env } from 'nestjs-env';

export class AppConfig {
  @Env('PORT', { default: 3000 })
  port: number;

  @Env('NODE_ENV')
  env: string;

  get isDevelopment() {
    return this.env === 'development';
  }
}

Let's register the config module in app.module.ts

import { Module } from '@nestjs/common';
import { EnvModule } from 'nestjs-env';
import { AppConfig } from 'src/config';

@Module({
  imports: [EnvModule.register([AppConfig])],
})
export class AppModule {}

Usage

Now we are ready to inject our AppConfig anywhere we'd like.

import { AppConfig } from 'src/config';

@Injectable()
class AppService {
  constructor(private readonly appConfig: AppConfig) {
    console.log(this.appConfig.isDevelopment);
  }
}
import { AppConfig } from 'src/config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const config = app.get(AppConfig);

  await app.listen(config.port);
}

That's it!

CLI

The nestjs-env CLI is a command-line interface tool that helps you to build env example file.

$ nestjs-env generate
OptionsAliasDescriptionDefault
--filename-fName of the file to which the example will be written..env.example
--pattern-pTemplate string specifying the names of files with configs.config.ts
--ignore-iSpecify directory that should be excludednode_modules
--directory-dSpecifies the base directory from which file scanning beginssrc/
--output-oSpecify an output folder for generated file
--printPrints an output to the consolefalse

License

The MIT License (MIT)

2.1.2

1 year ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.0

3 years ago

1.0.0

4 years ago

0.0.3

4 years ago

0.0.1

4 years ago