简体   繁体   English

process.env 变量给我 undefined in node/typescript

[英]process.env variables give me undefined in node/typescript

My folder structure is like this:我的文件夹结构是这样的:

backend/src/index.ts后端/src/index.ts

backend/.env后端/.env

backend/environment.d.ts后端/environment.d.ts

the 3 files have the following contents:这 3 个文件具有以下内容:

//index.ts
import express, {Application} from 'express';
import {config} from 'dotenv';
import {set, connect} from 'mongoose';

config({path: __dirname + '../.env'});

const MONGO_KEY = process.env.MONGO_KEY;
const PORT = 5000;
const HOST = 'localhost';

const app: Application = express();

const initDB = (key: string): void => {
  set('useCreateIndex', true);
  set('useFindAndModify', false);
  connect(key, {useNewUrlParser: true, useUnifiedTopology: true})
    .then(() => console.log('MongoDB connected!'))
    .catch((err: Error) => console.log(err));
};

console.log(MONGO_KEY);
if (MONGO_KEY) {
  initDB(MONGO_KEY);
}

app.listen(PORT, HOST, () =>
  console.log(`App running at http://${HOST}:${PORT}`)
);

//.env
MONGO_KEY="some_string"

// environments.d.ts
declare global {
  namespace NodeJS {
    interface ProcessEnv {
      MONGO_KEY: string;
    }
  }
}

export {};

The console.log of MONGO_KEY gives me undefined. MONGO_KEY 的 console.log 给我未定义。 I tried most of the solutions I found here and nothing worked so far.我尝试了在这里找到的大部分解决方案,但到目前为止没有任何效果。 I have @types/node installed.我安装了@types/node。

A second problem is the if check (I want to get rid of that).第二个问题是 if 检查(我想摆脱它)。 In the environment.d.ts file, I said that MONGO_KEY is a string, but ts thinks it's a string or undefined.在environment.d.ts文件中,我说MONGO_KEY是字符串,但是ts认为是字符串还是undefined。 I feel like I have to import the file somewhere.我觉得我必须将文件导入某处。

EDIT: changing编辑:改变

config({path: __dirname + '../.env'});

to

config();

seemed to solve my problem.似乎解决了我的问题。 however, I changed it to that because it stopped working in the first place, so it's still weird.但是,我将其更改为那个,因为它首先停止工作,所以它仍然很奇怪。

EDIT 2: In case someone faces the same problem: I had routes imported from other files that had process.env variables in them and the dotenv.config() import was placed below those routes, so of course those variables were undefined.编辑 2:如果有人遇到同样的问题:我从其他文件导入了路由,其中包含 process.env 变量,并且 dotenv.config() 导入被放置在这些路由下方,所以这些变量当然是未定义的。

If your js file is /home/alex/foo.js , then your __dirname is /home/alex .如果你的 js 文件是/home/alex/foo.js ,那么你的__dirname就是/home/alex

This means that:这意味着:

config({path: __dirname + '../.env'});

will become:会变成:

config({path: '/home/alex../.env'});

My general advice is: don't concatenate paths manually, use path.join() for consistent cross-platform behavior that adds/removes the exact correct amount of slashes.我的一般建议是:不要手动连接路径,使用path.join()以获得一致的跨平台行为,添加/删除正确数量的斜线。

use this command in your scripts: node -r dotenv/config your_main-file_name.js在您的脚本中使用此命令:node -r dotenv/config your_main-file_name.js

for more details check out: https://www.npmjs.com/package/dotenv有关详细信息,请查看: https://www.npmjs.com/package/dotenv

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

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