Node+ExpressRouter -> CommonJS to ESM --> Import routes --> Error [ERR_MODULE_NOT_FOUND]: Cannot find module

I cant find my mistake after updating the node engine to 14.x and using ESM instead of CommonJS: exampleroute.js

import express from "express";
const router = express.Router();
router.get("/exampleroute", async (req, res) => {
  console.log('......')
})
export default router;

server.js

import http from "http";
import express from "express";
import exampleroute from "./routes/exampleroute";
const server = express();
server.use("/exampleroute", exampleroute);
const httpServer = http.createServer(server);
const httpPort = 8080
httpServer.listen(httpPort, () => console.log(`server is running @ port: ${httpPort}`));

Leads to: Error [ERR_MODULE_NOT_FOUND]: Cannot find module

What am I doing wrong?

Upvotes: 0

Views: 604

Answers (2)

When you are working with ESM instead of CommonJS you can differentiate the import of a directory from a package by using relative paths and also explicit file extension. In your case try with

import exampleroute from "./routes/exampleroute.js"

Upvotes: 0

rkJun
rkJun

Reputation: 481

Try using:

import exampleroute from "./routes/exampleroute.js";

ref. Can't import "mysql2/promise" into ES module (MJS) on Node.js 13 / 14

Upvotes: 1

Related Questions