es6 模块是否不需要 browserify/webpack?

Do es6 modules negate the need for browserify/webpack?

ES6 模块允许我们创建可以作为依赖项导出和导入的代码模块。

Browserify 和 Webpack 做同样的事情。所以我假设如果我使用 ES6 和 babel 之类的东西来转换我的代码,那么我就不需要 webpack 和 browserify 了吗?

如果在浏览器中使用,目前还需要webpack或者browserify

我们来看一个例子:

以下

import * as name from 'name.js';

变成:

'use strict';

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

var _nameJs = require('name.js'); // Here, a function named "require" is still needed

var name = _interopRequireWildcard(_nameJs);

Check it out in the Babel Repl

如你所见,babel 也依赖于 CommonJS Method require (really any implementation of it) to do the import. As node.js implements CommonJS, it would work, but no browser currently implements it. AFAIK there aren't any browsers that support ES 6 Modules natively

详述here - ES6 模块有两个方面:

The ES6 module standard has two parts:

  • Declarative syntax (for importing and exporting)
  • Programmatic loader API: to configure how modules are loaded and to conditionally load modules

Babel 只处理第一个方面 - 即。用于导入和导出的声明性语法,不提供自己的加载器。

今天使用 ES6 模块的人通常做以下事情之一:

  • 使用 Babel 将 ES6 模块语法转换为现有的模块实现,例如 CommonJS/AMD,然后可以使用 Webpack/browserify/requirejs 等可用工具来 load/bundle js 资产。
  • 或者像 SystemJS which provide support for Programmatic loader API (through ES6 module loader polyfill. Using this tool does allow you get rid of Browserify/Webpack but, as of now, you are just swapping one tool for another. It is likely that as more and more libraries like Aurelia 这样的加载器拥抱 ES6 模块,并推荐标准化的 System.import 语法 - SystemJS 将流行起来。

另一方面是与现有模块生态系统的兼容性(尤其是在 npm 上)。值得注意的是,您不会通过以下任一策略失去与现有生态系统的兼容性:webpack 和 SystemJS 都允许加载和捆绑 commonjs 以及 AMD 模块。

就资产捆绑而言,HTTP 2 中的持久连接支持已经显着降低了 javascript 文件串联的价值。尽管在对完整 javascript 包进行丑化后消除死代码仍然是一项有价值的优化。

正如 Rollup 等工具的作者反复指出的那样,ES6 模块的静态可分析特性使得 tree-shaking 和死代码消除更加有效。

目前我想说的有三点。如有不妥请指正...

  1. 如果你想为用户提供最好的性能,那么es6modules更好。在某些情况下它们确实表现得更好(更少的 http 请求,更好的缓存)并且 AFAIK 没有它们表现更差的情况。

  2. browserify 与目前最常用的包管理器集成得更好 — npm.

对于 es6modules,您必须在 node_modules 中指定模块的相对路径,而不是像 browserify 那样仅指定模块的名称。您可以编写一个预处理器来解决 es6modules 的这个问题,并在构建过程中执行它(如果它不是相对路径,它只会更改路径)。但这当然是额外的工作,browserify 提供了开箱即用的功能。

此外,npm 注册表中的大多数模块可能使用 commonjs 语法而不是 es6modules 语法。这意味着如果你想直接从 npm 使用模块,你必须 fork 它才能利用 es6modules 的好处。

注意:AFAIK 将 es6modules 语法转换为其他语法(例如使用 babel)并没有保留 es6modules 语法的优点。

  1. 当您使用 es6modules 时,您可能还会有某种构建过程(就像在第二点提到的,或者如果您还想缩小或做其他事情)。使用 browserify 可以使用非常好的工具,使开发变得非常方便,以便您可以以有效的方式工作,例如 watchify 确实会因缓存而显着增加构建所需的时间。