.env调用不同文件中的变量

我有一个.env文件,其中存储了两个不同的变量:

x=123
y=456

在同一文件夹中,我还有另外三个文件,下面带有树:

/folder
   /.env
   /config.js
   /app_setup.js
   /match_algo.js

在config.js文件中,我正在读取.env文件中的变量并将其导出:

const dotenv = require('dotenv');
const cfg = {};
dotenv.config({path: '.env'});

cfg.port = process.env.PORT;
cfg.x = process.env.x;
cfg.y = process.env.y;

module.exports = cfg;

在app.setup.js文件中,我使用的是来自.env的变量x

var firebase = require("firebase");
const Config = require('./config');

var config = {
  apiKey: Config.x
};
firebase.initializeApp(config);

module.exports = firebase;

在match_algo中,我正在使用.env中的变量y做其他事情:

const Router = require('express').Router;
const Config2 = require('./config');
const router = new Router();

exports.return_match_uid = function return_match_uid() {
  var variable2 = Config2.y;
.....

显然,不正确读取match_algo中的变量y。我的代码没有发现任何问题。

likunok 回答:.env调用不同文件中的变量

当您想给dotenv config设置路径时,您需要给出正确的路径。不只是import { observable,action,decorate } from "mobx"; class Field { name = ''; otherAttr = null; changeName(name) { this.name = name; } } decorate(Field,{ name: observable,otherAttr: observable,changeName: action }) 。看到这个

.env

希望这会有所帮助

本文链接:https://www.f2er.com/2844048.html

大家都在问