typescript - 打字稿 - 无法动态导入类
问题描述
我在一个名为“控制器”的文件夹中有一些类。从我的“main.ts”中,我列出了该“控制器”文件夹中的类并尝试动态导入它们。
每个类都使用“导出默认值”导出
我试过的:
- 从要导入的类中删除导出默认值
结果:
- 不抛出任何错误
- 富值:
{ 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)
}
}
});
这是我运行东西时的终端输出:
事情是打字稿我使用它来动态导入任何类我得到以下错误:
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>)
有人可以帮助我吗,提前谢谢!?
解决方案
抱歉耽搁了。由于这是内部后端框架的一些研发,而我工作的公司可以让我分享一些片段,这是我编写的代码:
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;
推荐阅读
- typescript - JEST MOCK - 测试所有路由后如何模拟函数
- c# - 如何在 HttpListener 上设置 TimeoutManager
- arrays - 从 Typescript 中的 json 检索数据
- css - 使用materialize.css时选择元素不出现
- android - Android 8 或 9 上的后台地理围栏不起作用
- ios - 如何将 Google Map 动画到当前标记位置并在 Swift 中绘制线条
- python - 保存已翻译的 django 模型翻译的 slug 不起作用
- rust - 是否可以在 WebAssembly 中使用 Rust 进行动态链接?
- powershell - 使用 Literalpath 或有意复制项目的错误?
- laravel - Laravel 4.2 Request::get() 为空