[英]Typescript - Unable to dynamically import a class
I have some classes in a folder named "controllers".我在名为“controllers”的文件夹中有一些类。 From my "main.ts", im listing classes from that "controllers" folder and trying to dynamically import them.在我的“main.ts”中,我列出了“controllers”文件夹中的类并尝试动态导入它们。
Each class is exported using "export default"每个类都使用“导出默认值”导出
What I've tried:我试过的:
Outcome:结果:
{ default: {} }
Foo 值: { default: {} }
./controllers/LoginController.ts ./controllers/LoginController.ts
export default class LoginController {
...
...
...
}
./main.ts ./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.导入/导出发生在编译/捆绑期间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.