【问题标题】:Typescript: dynamically import classes打字稿:动态导入类
【发布时间】:2018-08-15 04:25:28
【问题描述】:

我喜欢动态导入 Typescript 类。 我使用新的动态函数导入运行了所有内容,但是如何导入动态类?

我有一个有点脏的 hack,看起来是这样的:

// main.ts
async function main2() {
    const G = './test1'
    const TASK_IMPORT_FUNCTION = await import(G)
    const TASK_CLASS = TASK_IMPORT_FUNCTION.getTask()
    const TASK = new TASK_CLASS(__dirname)
    const R_TASK = TASK.run()
}
main2()

// test1.ts
export class Task {
    constructor(inputCwd: string) {}
    // ...
}

export function getTask() {
    return Task
}

所以我的问题是:如何摆脱 getTask() 函数并以动态方式直接导入类?

解决方案

// main.ts
async function main2() {
    const TASK_IMPORT = await import(G)
    const TASK_CLASS = TASK_IMPORT.Task
    const TASK = new TASK_CLASS(__dirname)
    const R_TASK = TASK.run()
}
main2()

【问题讨论】:

  • 如果你只写const TASK_CLASS = TASK_IMPORT_FUNCTION.Task会发生什么?
  • 这正在运行 :-) 那时我是盲人。非常感谢!

标签: typescript import


【解决方案1】:

像我一样

const x = (async () => {
  
  let file = "./v";

  const f = await import( file);
  return f;
})().then(f => {
  
  const s = new f.default();
  s.run();
})
  .catch(error => {
    // Handle/report error
    console.error(error);
  });


这里上课

export  default class V{
  constructor() {

  }
  run(){
    console.log("fire");
  }
}


【讨论】:

    【解决方案2】:

    假设Task类在task.ts,可以使用动态导入:

    const task = await import("./task");
    

    当您需要导入时。

    【讨论】:

      猜你喜欢
      • 2019-11-10
      • 2020-05-21
      • 2012-12-26
      • 2018-08-15
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2019-04-11
      • 2020-12-03
      相关资源
      最近更新 更多