ES6:有条件和动态导入语句 [英] ES6: Conditional & Dynamic Import Statements
问题描述
是否有条件导入语句如下?
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?
推荐答案
您无法动态解析依赖关系,因为 import
用于静态分析。但是,您可以在这里使用一些 require
,例如:
You can't resolve dynamically your dependencies, as imports
are meant for static analysis. However, you can probably use some require
here, something like:
for (let foo in bar) {
if (bar.hasOwnProperty(foo)) {
const Baz = require(foo).Baz;
}
}
这篇关于ES6:有条件和动态导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!