繁体   English   中英

打字稿 - 无法动态导入类

[英]Typescript - Unable to dynamically import a class

我在名为“controllers”的文件夹中有一些类。 在我的“main.ts”中,我列出了“controllers”文件夹中的类并尝试动态导入它们。

每个类都使用“导出默认值”导出

我试过的:

  • 从要导入的类中删除导出默认值

结果:

  • 不抛出任何错误
  • Foo 值: { 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;

打字稿导入/导出功能不是在运行时发生的 - 因此通过这种方式动态导入是不可能的。

导入/导出发生在编译/捆绑期间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM