简体   繁体   English

process.env.PORT 未定义。 typescript出现的问题

[英]process.env.PORT is Undefined. Problem occurring in typescript

I am new to typescript.我是 typescript 的新用户。

Imported and used dotenv package but still getting undefined It is necessary to declare interface for the dotenv variables?导入并使用了 dotenv package 但仍然未定义是否有必要为 dotenv 变量声明接口?

import express,{Application} from 'express';
import bodyParser from 'body-parser';
import  dotenv from 'dotenv';
dotenv.config();

const app : Application = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

console.log(process.env.PORT);   //undefined

app.listen(3000, ()=>console.log(`server started on 

http://localhost:${3000}`));

.env File .env 文件

PORT = 3000
SECRET=SOME_SECRET

package.json package.json

{
  "dependencies": {
    "body-parser": "^1.20.1",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "nodemon": "^2.0.20",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.4"
  },
}

You don't have to declare interfaces for environment variables in Typescript. Where's your.env file located relative to the Typescript file you pasted?您不必在 Typescript 中为环境变量声明接口。您的 .env 文件相对于您粘贴的 Typescript 文件位于何处?

The.env file should be at the project's root, in the same directory as the project's package.json file. .env 文件应该位于项目的根目录中,与项目的package.json文件位于同一目录中。 If it's located somewhere that's not the root or that dotenv can't figure out, I'd recommend using the following example for configuring dotenv:如果它位于不是根目录或dotenv无法识别的位置,我建议使用以下示例来配置 dotenv:

dotenv.config( { path: '../relative/path/.env' });

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

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