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.
To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);
TypeScript 2.4 added support for dynamic import() expressions, which allow us to asynchronously load and execute ECMAScript modules on demand. This means that we can conditionally and lazily import other modules and libraries.
The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With