Dynamically import a module into TypeScript

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

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

But it seems that the TypeScript compiler would like to see the 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 that I can, for example, use RequireJS directly (if I use the amd module format), but this does not seem right to me - this is a solution for one specific library.

+4
source share
2 answers

You need to specify a string encoded string. Variables will not work because this means that the code must exist outside of the define call that typescript will generate for you. All of your file code should really be "inside" this define call to generate javascript. :)

However, you can do it yourself if you do not use the typescript function of AMD and just use requirejs.d.ts

+6
source

ES offer dynamic imports supported with TypeScript 2.4. The document is here .

Function

import synchronized 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 } 
+3
source

Source: https://habr.com/ru/post/1495873/


All Articles