使用ES6语法动态导入JavaScript模块?

前端之家收集整理的这篇文章主要介绍了使用ES6语法动态导入JavaScript模块?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > ES6 variable import name in node.js?                                    9个
是ES2015,我该如何动态导入模块?

例如.代替…

import {SomeClass} from 'lib/whatever/some-class';

我不知道运行时的路径,所以我希望将路径存储在变量中,并且我想从该模块导入特定的东西:

function doDynamicStuff(path) {
    let importedThing = ...; //import * as importedThing from path;
    let thingIReallyWant = importedThing.someExportedVariable;

    ...
}

我不确定使用什么语法,或者根本不可能这样做.我尝试使用let importedThing = require(path);但是我们没有使用RequireJS.

最佳答案
ES2015不支持按设计进行动态导入.

In current JavaScript module systems,you have to execute the code in order to find out what the imports and exports are. That is the main reason why ECMAScript 6 breaks with those systems: by building the module system into the language,you can syntactically enforce a static module structure.

A module’s structure being static means that you can determine imports and exports at compile time (statically) – you only have to look at the source code,you don’t have to execute it.

ECMAScript 6 modules: the final syntax

要动态导入模块,您必须明确使用模块加载器(如RequireJS或SystemJS)

原文链接:https://www.f2er.com/js/429031.html

猜你在找的JavaScript相关文章