【问题标题】:Environment variable with dotenv and TypeScript带有 dotenv 和 TypeScript 的环境变量
【发布时间】:2020-09-28 22:22:04
【问题描述】:

我创建了这个.env 文件:

TYPE=xxx
HOST=xxx,
PORT=xxx,
USERNAME=xxx,
PASSWORD=xxx,
DATABASE=xxx,

在我的文件中我是这样使用的:

import * as dotenv from "dotenv";

dotenv.config();

export const typeOrmConfig: TypeOrmModuleOptions = {
    port: process.env.PORT
}

但我只能使用 .env 文件中的 port 变量,而我不能使用其余变量, 有人能告诉我为什么我不能使用我的其他变量吗?

【问题讨论】:

  • 你是什么意思,你不能使用它们?它们是未定义还是抛出某种错误。
  • 未定义所有这些
  • 您必须将 typeOrmConfig 导出为函数而不是 json,否则在运行时它将是未定义的。这些值是在编译时分配的。 (请看下面的解决方案)。

标签: javascript node.js typescript nestjs dotenv


【解决方案1】:

其实你已经定义了.env文件的路径

这样试试

import * as dotenv from "dotenv";
dotenv.config({ path: __dirname+'/.env' });

也试试这个

require('dotenv').config({ path: __dirname+'/.env' });

根据需要更改.env文件的路径

参考:https://www.npmjs.com/package/dotenv

【讨论】:

  • 终于,英雄终于来了!
【解决方案2】:

如果这是一个 React 应用程序并且您正在使用 react-script,则需要在键前加上 REACT_APP_ 前缀,否则它们将被忽略。

REACT_APP_TYPE=xxx
REACT_APP_HOST=xxx
REACT_APP_PORT=xxx
REACT_APP_USERNAME=xxx
REACT_APP_PASSWORD=xxx
REACT_APP_DATABASE=xxx

参考 -> https://create-react-app.dev/docs/adding-custom-environment-variables/

【讨论】:

  • 我不知道你为什么只得到减分......经过数小时的研究,你的评论拯救了我的一天......
  • 这帮助了我并节省了时间。不错的收获!
  • @ÁdámBukovinszki 否决票可能是因为 OP 询问的是 NestJS 应用程序,而不是 React 应用程序
【解决方案3】:

你可以使用内置的 NestJs 方式来处理这个(ConfigModule)。

Configuration | NestJs

// main.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { InventoriesModule } from './inventories/inventories.module';
import typeORMConfig from './config/database.config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PrismaModule } from './prisma/prisma.module';

@Module({
  imports: [
    ConfigModule.forRoot(), // load .env file
    TypeOrmModule.forRoot(typeORMConfig()),
    InventoriesModule,
    PrismaModule
  ],
})
export class AppModule { }


// ./config/database.config

import { TypeOrmModuleOptions } from '@nestjs/typeorm';

export default function (): TypeOrmModuleOptions {
    return {
        'type': 'mysql',
        'host': process.env.DB_HOST,
        'port': 3306,
        'username': process.env.DB_USERNAME,
        'password': process.env.DB_PASSWORD,
        'database': process.env.DB_DATABASE,
        'entities': ['dist/**/*.entity{.ts,.js}'],
        'synchronize': false
    }
};

【讨论】:

    【解决方案4】:

    我的项目有eslint 设置,所以我必须禁用import/first 规则

    /* eslint-disable import/first */
    require('dotenv').config();
    
    import Koa from 'koa';
    
    import { Logger } from './utils/loggers';
    import { app } from './app';
    
    const LOGGER = Logger();
    const port = parseInt(process.env.PORT as string, 10) || 8081;
    
    const server = (server: Koa) => {
      server.listen(port, () => {
        LOGGER.info(`> Ready on http://localhost:${port}`);
      });
    };
    
    server(app());
    
    

    我们也可以使用:

    import 'dotenv/config'
    

    但是

    require('dotenv').config({path:path_to_dotenv});
    

    更灵活。

    【讨论】:

      【解决方案5】:

      如果你得到未定义的值,如果你使用 ES6,你需要按如下方式导入它(.env 文件必须在项目根目录下):

      如何在导入中使用 dotenv?

      1. 预加载dotenv:node --require dotenv/config index.js(注意:这种方式不需要导入dotenv)
      2. 导入 dotenv/config 而不是 dotenv(注意:您不需要调用 dotenv.config() 并且必须通过命令行传递选项或 使用这种方法的环境变量)
      3. 创建一个单独的文件,该文件将首先执行配置,如 #133 的此评论中所述

      您必须在项目的 app.ts 文件中导入(首先) 以快递为例:

      app.ts

      //here
      import 'dotenv/config'
      
      import express from 'express'
      import { userRouter } from './routes/user'
      
      const app = express()
      
      app.use(`/users`, userRouter)
      app.listen(process.env.PORT, () => {
          console.log(`running`)
      })
      

      现在在您项目的任何地方使用它

      read the documentation总是好的

      【讨论】:

      • Diego 的好方法。为了使您的示例更加可见,请将端口 4000 切换到某个变量(例如 process.env.PORT)。这将有助于其他人了解import dotenv/config 之后会发生什么。干杯
      【解决方案6】:

      你必须导入 dotenv 并在根文件的最顶部执行 dotenv.config()。

      尽早在您的应用程序中要求并配置 dotenv。 参考:dotenv-npm

      【讨论】:

        【解决方案7】:

        这是 Nestjs 设置环境变量的方式:

         npm install @nestjs/config
        

        该软件包在内部使用 dotenv 软件包,它将您机器中的所有环境变量放在一起。

        app.module.ts

        // configModule chooses the .env file, configservice extract the settings
        import { ConfigModule, ConfigService } from '@nestjs/config';
        
        
        @Module({
          imports: [
            // list your project's modules
            ConfigModule.forRoot({
              // this is set so we do not have to reimport the ConfigModule all over the place into other modules
              isGlobal: true,
              envFilePath: `.env.${process.env.NODE_ENV}`,
            }),
            // Notice we are not using TypeOrmModule.forRoot({})
            // we set this to get access to ConfigService through dependency injection system
            TypeOrmModule.forRootAsync({
              // this tell DI system, find the configService which has all of the config info
              inject: [ConfigService],
              useFactory: (config: ConfigService) => {
                return {
                  type: 'sqlite',
                  database: config.get<string>('DATABASE'),
                  synchronize: true,
                  entities: [User, Report],
                };
              },
            }),
        

        【讨论】:

          【解决方案8】:

          我也遇到过这个问题,直到我意识到我从一个与 .env 文件格式不同的 YAML 文件复制粘贴的环境值之前,我都快疯了。

          一个使用:,另一个使用=

          如果它可以帮助另一个开发者的灵魂:-)

          【讨论】:

            猜你喜欢
            • 2020-07-30
            • 2018-10-05
            • 1970-01-01
            • 2017-07-09
            • 2015-09-02
            • 2020-11-22
            • 1970-01-01
            • 2020-01-22
            • 2020-03-08
            相关资源
            最近更新 更多