Gruntfile.jsは.coffeeのほうが扱いやすい
Posted: Updated:
設定が肥大化したときにミスりやすい
WebStormぐらい賢いエディタ(IDE)を使っているときはよいのですが、簡素なエディタでちょいちょい編集したいときなどに、しょーじき、カンマとか波括弧(brace)の閉じを誤ることがあります。
This should properly search for:
- grunt.js or grunt.coffee grunt file in current or parent directories
- tasks written as .js or .coffee files
- init templates written as .js or .coffee files
そこでcowboy/gruntのIssuesを漁っていたところ、良い具合にCoffeeScriptをサポートした旨を発見しました。この変更はmasterの0.3.x系には取り込まれておらず、現在はdevelブランチにある0.4.0aにのみ適用されています。
ということで、Gruntfile.jsをGruntfile.coffeeに変更してみます。
(Before)JavaScript
例えば、自分のGruntfile.jsからの抜粋です。jst.compile.options.templateSettingsのあたりとか、ネストしまくりで波括弧の閉じが不穏な様相を呈しています。
grunt.initConfig({
yuidoc: {
dist: {
'name': 'Project Name',
'description': 'Project Description',
'version': '0.0.2',
'url': 'http://projecturl.com/',
options: {
paths: 'src/coffee',
outdir: 'docs',
syntaxtype: 'coffee',
extension: '.coffee'
}
}
},
// Build JavaScript
jst: {
compile: {
files: {
'dist/tmpl/templates.js': ['src/tmpl/*.html']
},
options: {
templateSettings: {
interpolate : /\{\{(.+?)\}\}/g
}
}
}
}
});
(After)CoffeeScript
上のJavaScriptをCoffeeScriptにコンパイルすると、このようになります。
grunt.initConfig
yuidoc:
dist:
name: 'Project Name'
description: 'Project Description'
version: '0.0.2'
url: 'http://projecturl.com/'
options:
paths: 'src/coffee'
outdir: 'docs'
syntaxtype: 'coffee'
extension: '.coffee'
jst:
compile:
files:
'dist/tmpl/templates.js': ['src/tmpl/*.html']
options:
templateSettings:
interpolate: /\{\{(.+?)\}\}/g
記号の類が減って、シンプルになります。コンパイルするまでもなく、gruntがGruntfile.coffeeを解釈してくれるので、手間も何もありません。ただ記法がシンプルになるだけなので、ここだけ抜粋するとYAMLファイルのような趣ですね。
これなら閉じ間違いとか、カンマの位置とか気にしなくてはいけないストレスの類がいくらか軽減されるのではないでしょうか。CoffeeScript、業務ではちょっと…という人もただの設定ファイルだと思えば気軽に使えると思います。
ということで.coffeeで運用する
ことにします。つまらないミスが減っておすすめですよ。
特にGruntfileの名前をオプションで指定しなくても、普通にgruntコマンドを打てば自動で.coffeeも検出してくれます。あとは、taskもCoffeeScriptで書けるみたいなので、そのへんもやってみようと思う次第。