我需要做一些类似的事情:

if (condition) {
    import something from 'something';
}
// ...
if (something) {
    something.doStuff();
}

上面的代码不能编译;它抛出SyntaxError:…“import”和“export”只能出现在顶层。

我尝试使用系统。导入如下所示,但我不知道系统来自哪里。是ES6提案最终没有被接受吗?那篇文章中的“程序化API”链接把我扔到了一个废弃的文档页面。


当前回答

如果你愿意,你可以使用require。这是一种使用条件require语句的方法。

let something = null;
let other = null;

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

其他回答

你可以通过下面的链接了解更多关于动态导入的知识

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports

看起来答案是,就目前而言,你不能。

http://exploringjs.com/es6/ch_modules.html#sec_module-loader-api

我认为其目的是尽可能地支持静态分析,而有条件地导入模块则打破了这一点。另外值得一提的是——我使用的是Babel,我猜Babel不支持System,因为模块加载器API没有成为ES6标准。

我们现在有ECMA的动态进口建议。这是第三阶段。这也可作为babel预设。

以下是根据您的情况进行条件渲染的方法。

if (condition) {
    import('something')
    .then((something) => {
       console.log(something.something);
    });
}

这基本上返回了一个承诺。决议的承诺是有预期的模块。该建议还具有其他功能,如多个动态导入,默认导入,js文件导入等。您可以在这里找到关于动态导入的更多信息。

如果你使用动态导入Webpack模式,重要的区别是:

if (normalCondition) {
  // this will be included to bundle, whether you use it or not
  import(...);
}

if (process.env.SOMETHING === 'true') {
  // this will not be included to bundle, if SOMETHING is not 'true'
  import(...);
}

如果你愿意,你可以使用require。这是一种使用条件require语句的方法。

let something = null;
let other = null;

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