我需要做类似的事情:
if (condition) {
import something from 'something';
}
// ...
if (something) {
something.doStuff();
}
上面的代码无法编译;它抛出SyntaxError: ... 'import' and 'export' may only appear at the top level
.
我尝试使用System.import
如图所示here http://www.2ality.com/2013/07/es6-modules.html#module-loader-api,但我不知道在哪里System
来自。这是一个最终没有被接受的 ES6 提案吗?那篇文章中指向“编程 API”的链接将我转至已弃用的文档页面 http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders.
我们现在确实有 ECMA 的动态导入提案。这是在第 3 阶段。这也可以作为babel 预设 https://babeljs.io/docs/plugins/syntax-dynamic-import/.
以下是根据您的情况进行条件渲染的方法。
if (condition) {
import('something')
.then((something) => {
console.log(something.something);
});
}
这基本上返回一个承诺。预计解析承诺会有该模块。该提案还具有其他功能,例如多个动态导入、默认导入、js 文件导入等。您可以找到有关的更多信息此处动态导入 http://2ality.com/2017/01/import-operator.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)