javascript - 简单的 JavaScript ES6 与 require() 导入

标签 javascript ecmascript-6 browserify babeljs javascript-import

我正准备通过 babel 使用 ES6 模块导入/导出,但在 article 中遇到了这个令人困惑的声明.

它指出:

The power of ES6’s import and export combined with the require() 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 的标志。这可以是 truefalse .因此,如果应用程序需要加载它们,您将需要加载它们:

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/

相关文章:

javascript - browserify包: how to expose library inside window object?

javascript - vuejs v-model 让它只从一处改变

javascript - 增加 HTML/CSS/JS 中输入字段的大小

javascript - 根据数组元素从数组中提取元素

css - 具有通用模块 css 的 browserify-css

javascript - 无法在 React 中包含 3-d 方组件

javascript - 尝试让一个函数返回另一个函数,该函数返回两个参数的总和

javascript - 在原型(prototype)继承中创建新对象时如何覆盖函数?

javascript - 如果值不满足给定条件,如何将其他数组元素包含到新数组中

javascript - 默认情况下尝试使用 state react es6 隐藏 <p> 标签