我正准备通过 babel 使用 ES6 模块导入/导出,但在 article 中遇到了这个令人困惑的声明.
它指出:
The power of ES6’s
import
andexport
combined with therequire()
method, gives us the freedom to organize all of the client-side code into modules and at the same time write the code using all the power of the new version of JavaScript.
这听起来像是 ES6 的系统和 require()
服务于两个不同的目的,从而使这种 babel/browserify
方法成为最好的方法。我的理解是他们都做同样的事情,只是有点不同。谁能帮忙解释一下?
最佳答案
这个说法自相矛盾。如果你进入 ES6/ES7,你将不想使用 CommonJS-style require
,但您总是希望使用 import
异步加载模块.
事实上,ES6/ES7 有一个导入模块的编程方式:System.import(...)
,但是 loader specification还在讨论中……
在它获得推荐状态之前,有一个 polyfill(还有更多...):SystemJS .
从现在开始我会避免使用任何其他模块加载语法,因为几年后您的代码将在标准 Web 浏览器中完全可执行,只需进行少量修改。
OP 在一些评论中问...
Why will System.import(...) from ES6 be needed for js modules when we have the ES6 import/export module loading capabilities? Aren't they performing the same tasks?
import
语句只能位于代码文件的顶部。有时您知道根据执行某种逻辑要加载哪些文件,并且 import
语法不支持条件。
例如,假设您有一个需要插件 的应用程序,并且某些选项有一个名为loadPlugins
的标志。这可以是 true
或 false
.因此,如果应用程序需要加载它们,您将需要加载它们:
if(options.loadPlugins) {
Promise.all(
options.plugins.map(plugin => System.import(plugin.path))
).then(() => {
// Do stuff when all plugins have been already loaded!
});
}
关于javascript - 简单的 JavaScript ES6 与 require() 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39054481/