I'm using TypeScript and Express to create an API that follows the principles of Clean Architecture. I separated each route of my application in a folder, and then I import all of them into an index.ts
file, merging each one inside an unique router and exporting the same. My problem is that the importation of this unique file is returning undefined
.
I think that is isn't a problem of my code itself, since TypeScript can infer correctly the type of the imported file and doesn't report any error during development. The only error I get just happens when trying to run the code:
TypeError:
app.use()
requires a middleware function
This is the code snippet that causes the error:
// expressInstance.ts --> Imported by the "server.ts" file, where listening the server happens
import express from "express";
import cors from "cors";
import { router } from ".."; // File with all the routes
const expressInstance = express();
expressInstance.use(express.urlencoded({extended: false}));
expressInstance.use(express.json());
expressInstance.use(cors());
expressInstance.use(router); // Line where the error appears
export {
expressInstance
};
And this is the code of the imported router
file:
// index.ts
import { Router } from "express";
import { userRouter } from "./user.routes";
import { postRouter } from "./post.routes";
const router = Router();
router.use("/user", userRouter);
router.use("/post", postRouter);
export {
router
};
I read in another question that the undefined
return used to happen at Express version 3, but I use the 4.17.13
version, so I think this isn't the cause of the problem. In fact, I have no idea what could be. I tried to see the router content by using console.log(router)
in the index.ts
file (before being imported by expressInstance.ts
), but it didn't work, because the code wasn't even executed.