当前位置:网站首页>Use of dotenv in nestjs

Use of dotenv in nestjs

2022-06-23 22:06:00 Swing a knife North

Dotenv Is a zero dependency module , It can change the variables in the environment variables from .env File loading to process.env in .

Use Install... In the project dotenv

npm install dotenv -S

Created in the root directory .env file

HOST=localhost 
PORT=3000 
MONGOOSE_URL=mongodb://localhost:27017/test 

The root directory app.js Lower introduction dotenv And use

require('dotenv').config({ path: '.env' })

//  Use 
console.log(process.env.HOST) // localhost
console.log(process.env.PORT) // 3000
console.log(process.env.MONGOOSE_URL) // mongodb://localhost:27017/test

How to be in nestjs Use in dotenv Well ?

stay nestjs Using environment variables in , It is recommended to use the official @nestjs/config, Open the box :

@nestjs/config Depend on dotenv, Can pass key=value Configure environment variables as , The project will load... In the root directory by default .env file , We just need to app.module.ts Introduction in ConfigModule, Use ConfigModule.forRoot() The method can , then ConfigService Read the relevant configuration variables .

  1. First install the corresponding npm package
  2. Configure environment variable files
  3. Define functions that read environment variables
  4. To configure @nestjs/config Methods

First installation @nestjs/config

Configure environment variable files , Configure two files , A development environment , One for the production environment .en file ,.en.prod file

//  Database address 
DB_HOST=localhost  
//  Database port 
DB_PORT=3306
//  Database login name 
DB_USER=root
//  Database login password 
DB_PASSWD=root
//  Database name 
DB_DATABASE=blog

.env.prod In is the database information to be used on the line , If your project is to be uploaded to online management , For security reasons , It is recommended that this file be added to .gitignore in . Then create a folder under the root directory config( And src At the same level ), Then create another env.ts It is used to read the corresponding configuration files according to different environments .

This file is used to determine whether the current environment is a development environment or a test environment :

import * as fs from 'fs';
import * as path from 'path';
const isProd = process.env.NODE_ENV === 'production';

function parseEnv() {
  const localEnv = path.resolve('.env');
  const prodEnv = path.resolve('.env.prod');

  if (!fs.existsSync(localEnv) && !fs.existsSync(prodEnv)) {
    throw new Error(' Missing Environment Profile ');
  }

  const filePath = isProd && fs.existsSync(prodEnv) ? prodEnv : localEnv;
  return { path:filePath };
}
export default parseEnv();

The file execution above returns an object :

{path:' Environment variables file '}

Then configure @nestjs/config Methods

import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigService, ConfigModule } from '@nestjs/config';
import envConfig from '../config/env';

@Module({
  imports: [
    ConfigModule.forRoot({ 
    isGlobal: true,  //  Set to global 
    envFilePath: [envConfig.path] 
   }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'mysql', //  Database type 
        entities: [],  //  Data table entities 
        host: configService.get('DB_HOST', 'localhost'), //  host , The default is localhost
        port: configService.get<number>('DB_PORT', 3306), //  Port number 
        username: configService.get('DB_USER', 'root'),   //  user name 
        password: configService.get('DB_PASSWORD', 'root'), //  password 
        database: configService.get('DB_DATABASE', 'blog'), // Database name 
        timezone: '+08:00', // The time zone configured on the server 
        synchronize: true, // Automatically create database tables based on entities ,  It is recommended to shut down the production environment 
      }),
    }),
    PostsModule,
  ],
 ...
})
export class AppModule {}

ConfigModule Of forRoot The function parameter is an object , The more important attribute is isGlobal and envFilePath, This envFilePath It is the environment variable configuration file read according to the environment variables .

How to read process.env Well ? Call directly configService Of get Method ,get The first parameter of the method is the environment variable attribute , The second parameter is the default value .

This is where nestjs Use in dotenv Methods , I hope it helped you .

原网站

版权声明
本文为[Swing a knife North]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112200837452342.html