ES6:条件&动态导入语句 [英] ES6: Conditional & Dynamic Import Statements

查看:17
本文介绍了ES6:条件&动态导入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以有如下条件导入语句?

Is it possible to have conditional import statements like below?

if (foo === bar) {
    import Baz from './Baz';
}

我已经尝试了上述方法,但在编译时出现以下错误(来自 Babel).

I have tried the above but get the following error (from Babel) when compiling.

'import' and 'export' may only appear at the top level

动态

是否可以有如下动态导入语句?

Dynamic

Is it possible to have dynamic import statements like below?

for (let foo in bar) {
    if (bar.hasOwnProperty(foo)) {
        import Baz from `./${foo}`;
    }
}

上面在编译时从 Babel 收到同样的错误.

The above receives the same error from Babel whilst compiling.

这是可能的还是我遗漏了什么?

Is this possible to do or is there something I am missing?

我尝试这样做的原因是我有许多页面"的导入,并且它们遵循类似的模式.我想通过使用动态 for 循环导入这些文件来清理我的代码库.

The reason I am trying to do this is that I have a lot of imports for a number of "pages" and they follow a similar pattern. I would like to clean up my code base by importing these files with a dynamic for loop.

如果这是不可能的,那么有没有更好的方法来处理 ES6 中的大量导入?

If this is not possible then is there a better way to handle large number of imports in ES6?

推荐答案

我们现在有了 ECMA 的动态导入提案.这是在第 2 阶段.这也可用作 babel-preset.

We do have dynamic imports proposal now with ECMA. This is in stage 2. This is also available as babel-preset.

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

Following is way to do conditional rendering as per your case.

if (foo === bar) {
    import('./Baz')
    .then((Baz) => {
       console.log(Baz.Baz);
    });
}

这基本上返回了一个承诺.承诺的决议有望有模块.该提案还包含多个动态导入、默认导入、js 文件导入等内容.您可以找到有关 此处是动态导入.

This basically returns a promise. Resolution of promise is expected to have the module. The proposal also has things like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.

这篇关于ES6:条件&动态导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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