从 Babel AST 生成 ES6 代码而不是 ES5 代码

Produce ES6 code rather than ES5 code from Babel AST

我想用 S.<name>(<expr>)(<expr>) 替换源文件中出现的所有 S.<name>(<expr>, <expr>)。我用 Esprima 和 Escodegen 写了一些东西来处理我的简单测试用例,但是当我给它一个包含 JSX 和其他非标准结构的文件时失败了。我将代码重写为 Babel 插件:

'use strict';

module.exports = function(babel) {
  return {visitor: {CallExpression: applyOneByOne}};

  function applyOneByOne(path) {
    if (path.node.arguments.length > 1 &&
        path.node.callee.type === 'MemberExpression' &&
        path.node.callee.object.type === 'Identifier' &&
        path.node.callee.object.name === 'S') {
      path.replaceWith (path.node.arguments.reduce (function(expr, arg) {
        return babel.types.callExpression (expr, [arg]);
      }, path.node.callee));
    }
  }
};

这可行,但 Babel 默认生成 ES5 输出。我想更新 ES6 源代码本身。是否可以从 Babel AST 生成 ES6 代码而不是 ES5 代码?如果是,怎么做?

那应该由预设控制。

最简单的方法是使用 babel-preset-env 并为其提供所需的环境预设。

例如,

代码:

class A {
  constructor() {
    console.log('example');
  }
}

使用预设 es-2015 时 gives:

'use strict';

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var A = function A() {
  _classCallCheck(this, A);

  console.log('example');
};

但是当使用预设 es-2016 时 gives:

class A {
  constructor() {
    console.log('example');
  }
}