Babel 对我的 Javascript 没有影响

Babel has no effect on my Javascript

我正在关注 Get To Know Babel The JavaScript Compiler Tutorial,这是我的 polygon.js

class Polygon {  
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  getArea() {
    return this.calcArea()
  }

  calcArea() {
    return this.height * this.width;
  }
}

我运行

babel polygon.js -o output.js
cat output.js | pbcopy

正在粘贴:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  getArea() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}

我期待转译为 ES5,但代码保持不变。

怎么回事?

$ .babel --version
6.2.0 (babel-core 6.2.1)

编辑:我用 npm install babel-preset-2015 -g

安装了预设
~/es6:.babel polygon.js -o output.js --presets es2015
Error: Couldn't find preset "es2015" relative to directory "."
    at OptionManager.mergePresets (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:327:17)
    at OptionManager.mergeOptions (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:287:12)
    at OptionManager.init (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:416:10)
    at File.initOptions (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:190:75)
    at new File (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:121:22)
    at Pipeline.transform (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
    at transform (/usr/local/lib/node_modules/babel-cli/lib/babel/util.js:53:22)
    at Object.compile (/usr/local/lib/node_modules/babel-cli/lib/babel/util.js:62:12)
    at /usr/local/lib/node_modules/babel-cli/lib/babel/file.js:130:23
    at arrayEach (/usr/local/lib/node_modules/babel-cli/node_modules/lodash/index.js:1289:13)

编辑:安装后的-g 是问题所在。我在本地安装并且可以使用。

这也引起了我的注意。新版本的 Babel 需要你安装一个预设,大概 the ES2015 one,并在 CLI 命令中明确指定。

根据 Babel 的安装位置 (globally/locally),这就是您需要安装预设的位置:

npm install babel-preset-es2015

然后你可以运行 Babel。例如,这会使用预设将一个文件夹中的所有文件转换为另一个文件夹。

babel [srcFolder] --out-dir [outFolder] --presets es2015