require('dotenv').config() 有什么作用?

问题描述

我知道 dotenv 模块与 nodejs 中的环境变量有关

require("dotenv").config();

而且我知道我应该将此代码放在我的 nodejs 服务器文件中。 但问题是我不明白配置方法实际上在做什么?

    export interface DotenvConfigOptions {

  path?: string;

  encoding?: string;

  debug?: boolean;
}

export interface DotenvConfigOutput {
  error?: Error;
  parsed?: DotenvParSEOutput;
}

/**
 * Loads `.env` file contents into {@link https://nodejs.org/api/process.html#process_process_env | `process.env`}.
 * Example: 'KEY=value' becomes { parsed: { KEY: 'value' } }
 *
 * @param options - controls behavior
 * @returns an object with a `parsed` key if successful or `error` key if an error occurred
 *
 */
export function config(options?: DotenvConfigOptions): DotenvConfigOutput;
/** @deprecated since v7.0.0 Use config instead. */
export const load: typeof config;

我查看了 config 函数,但我不明白这段代码是做什么的?

解决方法

您正在查看类型声明文件,但您应该查看编写为 here 的实际 config 实现。

但是,config 方法将 .env 文件路径作为参数,它会解析它并在 process.env 中设置该文件中定义的环境变量。

类型声明文件是 Typescript 概念,它允许您为已经编写的 Javascript 代码设置具体的变量/参数类型。