node.jstypescripttypescript2.0

Dynamic TypeScript imports without using Promises


I have this situation. The reason they are dynamic is to prevent loading 10x the amount of code that I need to load to do a certain command-line task.

if (diagnostics) {
  require('./lib/cli-commands/run-diagnostics').run(sumanOpts);
}
else if (script) {
  require('./lib/cli-commands/run-scripts').run(sumanConfig, sumanOpts);
}
else if (tscMultiWatch) {
  require('./lib/cli-commands/run-tscmultiwatch').run(sumanOpts);
}
else if (repair) {
  require('./lib/cli-commands/run-repair').run(sumanOpts);
}
else if (postinstall) {
  require('./lib/cli-commands/postinstall').run(sumanOpts);
}
else{
  // etc etc
}

if I try a dynamic loading import call, I get this:

enter image description here

It's clearly going to return a Promise not the module.exports value.

Is there a way to use dynamic import syntax without asynchronous loading or no?


Solution

  • Just to add to Unional's correct answer, it is very easy to work with the Promise returning dynamic import syntax.

    (async function () {
      if (diagnostics) {
        const run = await import('./lib/cli-commands/run-diagnostics');
        run(sumanOpts);
      }
      else if (script) {
        const run = await import('./lib/cli-commands/run-scripts');
        run(sumanConfig, sumanOpts);
      }
    }());
    

    Note that if you are using --module commonjs modules then it is likely best to stick to require. However, the above is perfect for --module amd, --module system, and of course --module esnext.