簡體   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