我可以使用 Babel 转译为 ES5 但保留 import/export 而不是 commonjs 吗?

Can I use Babel to transpile to ES5 but keep import/export instead of commonjs?

我想创建一个使用 ES import/export 而不是 commonjs 交付模块的 npm 库(例如 lodash-es 就是这样)。如果我没记错的话,交付的代码必须是 ES5 并且具有 import/export.

我不知道如何配置 Babel 来做到这一点。我希望选项 targets.esmodules 可以解决问题。

当我在calc.js中有以下代码时:

// calc.js
export function add (a, b) {
    const result = a + b
    return result
}

和babel配置.babelrc:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "esmodules": true
        }
      }
    ]
  ]
}

当运行 babel:

babel calc.js

输出为:

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.add = add;

function add(a, b) {
  var result = a + b;
  return result;
}

这是 commonjs (exports.add)。选项 targets.esmodules 似乎没有效果。如何让 Babel 生成一个 es 模块 (export function add)?还是我误解了在 npm 上交付 ES 模块的想法?

它看起来像基于 the Rollup docs that you should indeed transpile a version that has only import/export, but has transpiled out all of the other non-ES5 syntax. The Webpack docs 说的类似的话。这种格式假定您的用户正在使用 Rollup 或 Webpack 等工具,这些工具本身支持 import/export 语句,但可能会将它们转换为 ES5 兼容语法,而无需 运行 您的库通过 Babel。

而且看起来 Redux 尤其能做到这一点 by using the Rollup format option and then in their .babelrc file they use the "modules": false option to tell Babel not to transpile module statements. It's not clear to me how Lodash manages it, since looking over their source code 我在 repo 的任何地方都没有看到任何构建脚本。