Traceur转码器是Google 公司的一款转码器,也可以将 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>
上面代码中,一共有 4 个script标签。第一个是加载 Traceur 的库文件,第二个和第三个是将这个库文件用于浏览器环境,第四个则是加载用户脚本,这个脚本里面可以使用 ES6 代码。
注意,第四个script标签的type属性的值是module,而不是text/javascript。这是 Traceur 编译器识别 ES6 代码的标志,编译器会自动将所有type=module的代码编译为 ES5,然后再交给浏览器执行。
除了引用外部 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));
正常情况下,上面代码会在控制台打印出9。
如果想对 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 的全局对象window.System,然后System.import方法可以用来加载 ES6。加载的时候,需要传入一个配置对象metadata,该对象的traceurOptions属性可以配置支持 ES6 功能。如果设为experimental: true,就表示除了 ES6 以外,还支持一些实验性的新功能。