I am moving an Express app across from CommonJS require
syntax to the ES6 module import
syntax. 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.
app.js
// importing environmental variables
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
let x = process.env.David;
console.log(x);
.env
David = test
import "dotenv/config.js";
对于所有文件中的.env
变量,请使用上述内容。
Try putting the env config in a separate file and import it first.
// 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. But actually it's easier move.env file to the project folder (projectName/.env) and use:
import "dotenv/config.js";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.