How to use dotenv and Express.js with ES6 modules


(Optional) Initialize git version control

git init

Initialize a new project and answer all questions

npm init

Install dotenv and express

npm i dotenv express

In package.json insert “type” : “module” to allow the import of modules like this

  "name": "demo",
  "version": "1.0.0",
  "type": "module",
  "description": "",

Create a file .env and insert

PORT=9000

Create a file server.js and insert

import dotenv from "dotenv";
import express from "express";

dotenv.config();

const app = express();
const port = process.env.PORT || 9000;

app.get('/', (req, res) => {
  res.send('Hello World!');
})

app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`);
})

Insert in a terminal

nodemon server.js


Leave a Reply

Your email address will not be published. Required fields are marked *