Google公司的Traceur转码器,可以将ES6代码转为ES5代码。

网页

Traceur允许将ES6代码直接插入网页,需要加载Traceur库文件

<script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
<script src="https://google.github.io/traceur-compiler/bin/BrowserSystem.js"></script>
<script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script>
<script type="module">
  import './Greeter.js';
</script>

上面代码,第一个是加载Traceur库文件,第二个和第三个是将这个库文件用于浏览器环境;第四个则是加载用户脚本。

第四个script标签的type属性是module,而不是text/javascript ,这是Traceur编译期识别ES6代码的标识。

也可以直接在网页中放置ES6代码

<script type="module">
  class Calc {
    constructor() {
      console.log('Calc constructor');
    }
    add(a, b) {
      return a + b;
    }
  }

  var c = new Calc();
  console.log(c.add(4,5));
</script>

如果需要对Traceur的行为有精确控制,可以采用下面参数配置。

<script>
  // Create the System object
  window.System = new traceur.runtime.BrowserTraceurLoader();
  // Set some experimental options
  var metadata = {
    traceurOptions: {
      experimental: true,
      properTailCalls: true,
      symbols: true,
      arrayComprehension: true,
      asyncFunctions: true,
      asyncGenerators: exponentiation,
      forOn: true,
      generatorComprehension: true
    }
  };
  // Load your module
  System.import('./myModule.js', {metadata: metadata}).catch(function(ex) {
    console.error('Import failed', ex.stack || ex);
  });
</script>

命令行转换

Traceur是Node的模块

$ npm install -g traceur

Traceur直接运行ES6脚本文件

$ traceur calc.js
Calc constructor
9

将ES6脚本转为ES5保存

$ traceur --script calc.es6.js --out calc.es5.js

为防止有些特性编译不成功,最好加上--experimental 选项

$ traceur --script calc.es6.js --out calc.es5.js --experimental

Node环境

Traceur的Node用法

var traceur = require('traceur');
var fs = require('fs');

// 将 ES6 脚本转为字符串
var contents = fs.readFileSync('es6-file.js').toString();

var result = traceur.compile(contents, {
  filename: 'es6-file.js',
  sourceMap: true,
  // 其他设置
  modules: 'commonjs'
});

if (result.error)
  throw result.error;

// result 对象的 js 属性就是转换后的 ES5 代码
fs.writeFileSync('out.js', result.js);
// sourceMap 属性对应 map 文件
fs.writeFileSync('out.js.map', result.sourceMap);

【参考】

1。 阮一峰:http://es6.ruanyifeng.com/\#docs/intro

results matching ""

    No results matching ""