I am new to typescript.
Imported and used dotenv package but still getting undefined It is necessary to declare interface for the dotenv variables?
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
PORT = 3000
SECRET=SOME_SECRET
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?
The.env file should be at the project's root, in the same directory as the project's package.json
file. 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.config( { path: '../relative/path/.env' });
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.