打字稿-无法动态导入类

时间:2019-06-28 12:09:56

标签: typescript class dynamic import

我在名为“ 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>)

有人可以帮我吗,谢谢!!

2 个答案:

答案 0 :(得分:1)

很抱歉延迟。由于这是内部后端框架的某种研发,而我所工作的公司可以与我分享一些摘要,因此我编写了以下代码:

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;

答案 1 :(得分:0)

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

导入/导出在编译/捆绑期间进行。