如何有条件地导入ES6模块? [英] How can I conditionally import an ES6 module?

查看:117
本文介绍了如何有条件地导入ES6模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行以下操作:

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.

推荐答案

如果你愿意,你可以使用require。这是唯一有条件导入的方法。

If you'd like, you could use require. This is the only way to have a conditional import.

if (condition) {
    var something = require('something');
    var other = require('something').other;
}
if (something && other) {
    something.doStuff();
    other.doOtherStuff();
}

这篇关于如何有条件地导入ES6模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆