问题描述
我需要做类似的事情:
if (condition) {
import something from 'something';
}
// ...
if (something) {
something.doStuff();
}
以上代码无法编译;它抛出 SyntaxError: ... 'import' 和 'export' 可能只出现在顶层
.
The above code does not compile; it throws SyntaxError: ... 'import' and 'export' may only appear at the top level
.
我尝试使用 System.import
如图所示 这里,但我不知道 System
来自哪里.它是一个最终没有被接受的 ES6 提案吗?那篇文章中指向编程 API"的链接将我转储到 已弃用的文档页面一>.
I tried using System.import
as shown here, but I don't know where System
comes from. Is it an ES6 proposal that didn't end up being accepted? The link to "programmatic API" from that article dumps me to a deprecated docs page.
推荐答案
我们现在有了 ECMA 的动态导入提案.这是在第 3 阶段.这也可用作 babel-preset.
We do have dynamic imports proposal now with ECMA. This is in stage 3. This is also available as babel-preset.
以下是根据您的情况进行条件渲染的方法.
Following is way to do conditional rendering as per your case.
if (condition) {
import('something')
.then((something) => {
console.log(something.something);
});
}
这基本上返回了一个承诺.承诺的决议有望有模块.该提案还具有其他功能,例如多个动态导入、默认导入、js 文件导入等.您可以找到有关 这里是动态导入.
This basically returns a promise. Resolution of promise is expected to have the module. The proposal also have other features like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.
这篇关于如何有条件地导入 ES6 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!