I am trying to use "module" type javascript with express-js first time. I am trying to create a book tracking application, but I am getting some error when I try to import routes in the main js file, it says cannot find module.
app.js:
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import mongoose from "mongoose";
// import routes
import authRoutes from "./routes/auth";
// db config
mongoose
.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("DB Connected"))
.catch((err) => console.log(err));
// constants
const app = express();
const port = process.env.PORT || 5001;
// middlewares
app.use(bodyParser.json());
app.use(cors());
// using routes
app.use("/api", authRoutes);
app.listen(port, () =>
console.log(`Server is running on http://localhost:${port}/`)
);
routes/auth.js:
import express from "express";
const router = express.Router();
router.get("/auth", (req, res) => {
res.send("Hello from auth");
});
export default router;
package.json:
{
"name": "server",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"type": "module",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.5"
}
}
Note: Other imports related to database models are all working fine!
Add js extension Node ESM does not work without it
import authRoutes from "./routes/auth.js";