decaffeinate - CoffeeScriptをES6へ変換
CoffeeScriptはJavaScriptでありがちな面倒くさい構文がシンプルになる便利な代替記法です。現在主流であるES5では使えない文法であるクラスであったり、テンプレートなどを先んじて使うこともできます。 しかしES6もnode上であれば十分に使えるようになってきています。そんな中、CoffeeScriptを使っていると古い文法のJavaScriptを生成するのは残念な感じです。そこで使ってみたいのがdecaffeinate、CoffeeScriptをES6に変換してくれるソフトウェアです。
decaffeinateの使い方
デモのコードです。クラスとテンプレートを使ってみました。
class ClassName
@staticVar: 0
@staticFunc: ->
console.log "Hello, I'm staticFunc"
constructor: (name)->
@name = name
publicFunc: ->
console.log "Hello, I'm publicFunc. my name is #{@name}"
c = new ClassName "Atsushi"
c.publicFunc()
これをデフォルトのCoffeeScriptで変換した結果は次のようになります。クラスを擬似的に再現しています。
// Generated by CoffeeScript 1.10.0
(function() {
var ClassName, c;
ClassName = (function() {
ClassName.staticVar = 0;
ClassName.staticFunc = function() {
return console.log("Hello, I'm staticFunc");
};
function ClassName(name) {
this.name = name;
}
ClassName.prototype.publicFunc = function() {
return console.log("Hello, I'm publicFunc. my name is " + this.name);
};
return ClassName;
})();
c = new ClassName("Atsushi");
c.publicFunc();
}).call(this);
続いてdecaffeinateを使った場合です。クラスがそのまま使えていますし、テンプレートも使われています。ES6ならではのコード量になっています。
class ClassName {
this.staticVar: 0;
static staticFunc() {
// do something...
return console.log("Hello, I'm staticFunc");
}
constructor(name){
this.name = name;
}
publicFunc() {
// do something...
return console.log(`Hello, I'm publicFunc. my name is ${this.name}`);
}
}
var c = new ClassName("Atsushi");
c.publicFunc();
decaffeinateはまだすべての機能に対応していませんので、プロダクトへの適用はまだ難しいでしょう。しかしdecaffeinateが完成すれば、これまでCoffeeScriptで書いていたコードはそのままES6として動くようになるでしょう。
decaffeinateはnode/JavaScript製のオープンソース・ソフトウェア(MIT License)です。