Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 496
Stan Prokop Avatar asked Aug 08 '13 05:08

Stan Prokop


People also ask

How do I import a module dynamically?

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);

What is dynamic imports in angular?

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.

What is dynamic import in Javascript?

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.


1 Answers

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 } 
like image 105
aleung Avatar answered Oct 19 '22 23:10

aleung