简体   繁体   中英

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:

在此输入图像描述

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?

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 .

By the nature of dynamic import, it is asynchronous.

require() is synchronous because it lives on the server side. You can read a file synchronously using (for example) fs.readFileSync() .

For the new dynamic import, it is designed to work on the client side so there will be an ajax request back to the server to perform the import.

Thus it has to be asynchronous.

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