import path from "path";
import express from "express";
import { performance } from "perf_hooks";
import fs from "fs";
const basename = path.basename(__filename);
class Routes {
async loadRoutes(app: express.Application) {
const t1 = performance.now();
return new Promise<void>(async (resolve, reject) => {
const files = fs.readdirSync(__dirname)
.filter((file: string) => {
return (
file.indexOf(".") !== 0 &&
file.indexOf("..") !== 0 &&
file.slice(-9, -3) === "Router" &&
file !== basename
);
});
console.log(`Found route files: ${files}`);
for (const fileName of files) {
try {
// const module = await import(`./${fileName}`);
const module = require(`./${fileName}`);
const route = module.default || module;
console.log(`Loaded module from ${fileName}:`, route);
if (typeof route === 'function') {
app.use(route);
console.log(`Route from file: ${fileName} loaded successfully`);
} else {
console.error(`Module from file: ${fileName} does not export a
valid route`);
}
} catch (err) {
console.error(`Failed to dynamically import ${fileName}`, err);
}
}
const t2 = performance.now();
console.log(`Routes loaded in ${t2 - t1}ms`);
resolve();
});
}
}
export default new Routes();
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"lib": ["ES6"],
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
},
"include": ["src/**/*"],
"exclude": ["node_modules", "src/database/client/**/*"]
}
Here is my tsconfig.json. Yes, it is set to module: commonjs, and if I change it to module or ESNext, the entire project breaks. However, the codebase is huge, and both import and require are frequently used throughout the project. Both work, even though it’s set to commonjs, so I don’t think that’s the problem. The console log of module.default for both import and require is exactly the same, and app.use works without error. If I pass something invalid to app.use, it rejects it, so it has to be a middleware. But when using require, the route exists; when using import, the route does not exist.