我有这种情况.它们是动态的原因是为了防止加载10倍我需要加载的代码量来执行某个命令行任务. if (diagnostics) { require('./lib/cli-commands/run-diagnostics').run(sumanOpts);}else if (script) { require('./l
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
}
如果我尝试动态加载导入调用,我得到这个:
它显然会返回Promise而不是module.exports值.
有没有办法在没有异步加载的情况下使用动态导入语法?
只是为了添加Unional的正确答案,使用Promise返回动态导入语法非常容易.(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);
}
}());
请注意,如果您使用的是–module commonjs模块,那么最好坚持使用require.但是,以上是完美的 – 模块amd, – 模块系统,当然 – 模块esnext.
