【问题标题】:How do I load dotenv in Typescript如何在 Typescript 中加载 dotenv
【发布时间】:2020-10-25 10:48:29
【问题描述】:

我正在尝试使用 Typescript 加载 .env 环境变量。

这是我的 .envapp.ts 文件

//.env

DB_URL=mongodb://127.0.0.1:27017/test
// app.ts

import * as dotenv from 'dotenv';
import express from 'express';
import mongoose from 'mongoose';

dotenv.config();
mongoose.connect(process.env.DB_URL, config);

当我使用ts-node src/app.ts 命令运行app.ts 时,抛出此错误

Unable to compile TypeScript:
src/app.ts:50:18 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(uris: string, callback: (err: MongoError) => void): Promise<typeof import("mongoose")>', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
      Type 'undefined' is not assignable to type 'string'.
  Overload 2 of 3, '(uris: string, options?: ConnectionOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
      Type 'undefined' is not assignable to type 'string'.

50 mongoose.connect(process.env.DB_URL, config);

但是当我在下面添加 if 语句时,效果很好

//app.ts
import * as dotenv from 'dotenv';
import express from 'express';
import mongoose from 'mongoose';

dotenv.config();

//Add this code
if (!process.env.DB_URL) {
  process.exit(1);
}

mongoose.connect(process.env.DB_URL, config);
Example app listening at http://localhost:3000
Mongoose default connection is open to  mongodb://127.0.0.1:27017/test

我想知道为什么下面的代码没有抛出这个错误?

【问题讨论】:

  • 你能把console.log('DB_URL=' + process.env.DB_URL)console.log('config=' + config)放在dotenv.config();之后并给出输出吗?

标签: mongodb typescript express


【解决方案1】:

从错误消息中,您可以得出结论,TypeScript 期望 mongoose.connect() 的第一个参数是 string,但环境变量可以是 stringundefined

通过添加条件,您消除了在您调用mongoose.connect(process.env.DB_URL, config)process.env.DB_URLundefined 的可能性

如果你确定它永远不会是undefined,你可以使用TypeScript Non-null assertion operator

mongoose.connect(process.env.DB_URL!, config);

提示:

代替

import * as dotenv from 'dotenv';
...
dotenv.config();

你可以这样做

import 'dotenv/config'

这将确保在下一个 import 语句之前设置环境变量,因此您只需在应用的主文件中执行此操作一次。

【讨论】:

  • import from 'dotenv/config' 应该是 import 'dotenv/config'
【解决方案2】:

这类问题已经有问题了。你可以看看这里。 Its is here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2018-06-05
    • 2018-02-27
    • 2018-09-27
    相关资源
    最近更新 更多