I have some classes in a folder named "controllers". From my "main.ts", im listing classes from that "controllers" folder and trying to dynamically import them.
Each class is exported using "export default"
What I've tried:
Outcome:
{ default: {} }
./controllers/LoginController.ts
export default class LoginController {
...
...
...
}
./main.ts
glob("**/*.controller.ts", {}, async function (er, paths: string[]) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
for (const path of paths) {
try {
const foo = require(`../${path}`)
console.log(foo)
} catch (e) {
console.log(e)
}
}
});
Here is the my terminal output when running the thing:
Thing is with typescript im using this to import any class dynamically i get the following error:
export default class LoginController {
[0] ^^^^^^
[0]
[0] SyntaxError: Unexpected token export
[0] at Module._compile (internal/modules/cjs/loader.js:703:23)
[0] at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
[0] at Module.load (internal/modules/cjs/loader.js:628:32)
[0] at Function.Module._load (internal/modules/cjs/loader.js:555:12)
[0] at Module.require (internal/modules/cjs/loader.js:666:19)
[0] at require (internal/modules/cjs/helpers.js:16:16)
[0] at /Users/absystech/Development/Absystech/espace client/backend/dist/main.js:25:29
[0] at Generator.next (<anonymous>)
[0] at /Users/absystech/Development/Absystech/espace client/backend/dist/main.js:8:71
[0] at new Promise (<anonymous>)
Could someone help me on this, thanks in advance !?
Sorry for the delay. Since it was some R&D for a in-house backend framework and the company I worked for is okay for me to share some snippets, here is what I coded:
import bodyParser from "body-parser";
import cors from "cors";
import * as dotenv from "dotenv";
import express from "express";
import path from "path";
import "reflect-metadata";
import { Logger } from "../@propulsion:helpers";
import Controllers from "./injectors/controller.injector";
import Responses from "./injectors/response.injector";
import Services from "./injectors/service.injector";
dotenv.config({ path: path.join(__dirname, "../../.env")});
const app = express();
app.use(cors({
exposedHeaders: ["Authorization", "x-token-regenerate"],
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("public/"));
const wrapAsync = (fn) => {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
};
const server: Promise<express.Application> = (async () => {
const [controllers, responses, services] = await Promise.all([
Controllers.getControllers(),
Responses.getResponses(),
Services.get(),
]);
for (const [index, response] of responses.entries()) {
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
const custom: CustomResponse = (data: ICustomResponse = {}) => {
return response.instance.bind({ req, res, Logger })(data);
};
(res as any)[response.name] = custom;
next();
},
);
}
controllers.forEach(
(controller: { name: string; instance: any; methodName?: string }) => {
const prefix = Reflect.getMetadata("prefix", controller.instance);
const routes: RouteDefinition[] = Reflect.getMetadata(
"routes",
controller.instance,
);
routes.forEach((route) => {
app[route.requestMethod](
prefix + route.path,
wrapAsync(async (req: express.Request, res: express.Response) => {
const instance = new controller.instance(services);
await instance[route.methodName](req, res);
}),
);
});
},
);
return app;
})();
export default server;
The typescript import/export functionality is not something that happens during runtime - therefore dynamic import via this way is not possible.
The import/export is happening during compile/bundle time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.