簡體   English   中英

TypeScript中動態導入模塊

[英]Dynamically import module in TypeScript

TypeScript 動態加載模塊的方式是什么(模塊的路徑在運行時已知)? 我試過這個:

var x = "someplace"
import a = module(x)

但似乎 TypeScript 編譯器希望在編譯時將路徑視為導入/模塊中的字符串:

$ tsc test.ts 
/tmp/test.ts(2,19): error TS1003: Identifier expected.
/tmp/test.ts(2,20): error TS1005: ';' expected.

我知道我可以例如直接使用 RequireJS(如果我使用 amd 模塊格式),但這對我來說感覺不對 - 它是一個特定庫的解決方案。

從 TypeScript 2.4 開始支持 ES 提案動態導入 文件在這里

import函數是異步的並返回一個Promise

var x = 'someplace';
import(x).then((a) => {
  // `a` is imported and can be used here
});

或者使用async/await

async function run(x) {
  const a = await import(x);
  // `a` is imported and can be used here
}

您需要指定一個硬編碼字符串。 變量將不起作用。

更新

JavaScript 現在有了動態導入。 所以你可以做import(x)https : //developers.google.com/web/updates/2017/11/dynamic-import

TypeScript 也支持它。 也就是說,您仍然希望參數可以靜態分析以確保類型安全,例如

const x = 'someplace';
import(x).then((a) => { // TypeScript knows that `x` is 'someplace' and will infer the type of `a` correctly
}); 

如果要從默認導出中動態提取類型,可以這樣做:

    const dynamicImport = await import('path-to-import')
    const typedDefaultImport = dynamicImport.default

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM