简体   繁体   English

不能将 dotenv 与 ES6 模块一起使用

[英]Can't use dotenv with ES6 modules

I am moving an Express app across from CommonJS require syntax to the ES6 module import syntax.我正在将 Express 应用程序从 CommonJS require语法移动到 ES6 模块import语法。 This is fine until I try and use dotenv to load my environment variables and every time I try to access these variables they come back as undefined.这很好,直到我尝试使用dotenv加载我的环境变量,并且每次我尝试访问这些变量时,它们都会返回未定义的状态。

app.js应用程序.js

// importing environmental variables
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';

let x = process.env.David;
console.log(x);

.env .env

David = test
import "dotenv/config.js";

对于所有文件中的.env变量,请使用上述内容。

Try putting the env config in a separate file and import it first.尝试将 env 配置放在一个单独的文件中并先导入它。

// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()


// index.js
import './loadEnv';
import express from 'express';
let x = process.env.David;
console.log(x);
 // importing environmental variables
        import express from 'express';
        import { config } from "dotenv";
        config({ path: process.ENV })
            
        let x = process.env.David;
        console.log(x);
import path from 'path';
import { fileURLToPath } from 'url';
import "dotenv/config.js";
    
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

dotenv.config({path:`${__dirname}/.env`});

I did this because my.env file was inside src folder (projectName/src/.env) and it was not detected by dotenv.我这样做是因为 my.env 文件位于 src 文件夹(projectName/src/.env)中,并且 dotenv 未检测到它。 But actually it's easier move.env file to the project folder (projectName/.env) and use:但实际上更容易将.env 文件移动到项目文件夹(projectName/.env)并使用:

import "dotenv/config.js";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM