简体   繁体   中英

Dynamically import module in TypeScript

What is the TypeScript way of loading modules dynamically (path to the module is known at runtime)? I tried this one:

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

But it seems that TypeScript compiler would like to see path as a string in import/module at compile time:

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

I know I can for example directly use RequireJS (if I use amd module format), but that doesn't feel right to me - it's solution for one particular library.

ES proposal dynamic import is supported since TypeScript 2.4. Document is here .

import function is asynchronous and returns a Promise .

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

Or using async/await :

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

You need to specify a hard coded string. Variables will not work.

Update

JavaScript now got dynamic imports. So you can do import(x) : https://developers.google.com/web/updates/2017/11/dynamic-import

TypeScript supports it as well. That said you would still want the argument to be statically analyzable for type safety eg

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

If you want to extract the type from a default export dynamically it can be done like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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