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
.
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