CoffeeScriptはじめました
飽きた件
この記事はNode.js止めようという方向で書いたものだったけど、 よくよく考えてみるとNode.jsが辛いのとJavaScriptが辛いのが混ざっている気がした。
というわけで、CoffeeScriptを試してみて「やっぱ辛いわー」と思ったら言語を変えることにしました。
JavaScriptとCoffeeScriptの併用
js2coffeeというものがあって、 JavaScriptをCoffeeScriptに変換することもできるのだけど、 今回は既存コードはJavaScriptのままで新しく書くものだけCoffeeScriptにするようにしました。
CoffeeScriptはJavaScriptへの変換処理が必要なので、 coffeeディレクトリをソース用に作り、destディレクトリに変換後のものを出力するようにした。
JavaScriptの置き場所も少し変えて、scriptからdest配下にコピーして使う想定。
. ├── gulpfile.js ├── dest │ ├── src │ └── test ├── coffee │ ├── src │ └── test └── script ├── src └── test
プログラムを実行する場合は、destディレクトリ以下を指定する。
Gulpで自動的に変換させる
WordPressのテーマ作成で使っているGulpをここでも使う。
gulpfileは拡張子を.coffee
にするとCoffeeScriptで書けた!
CoffeeScriptを始めるための設定が、はじめて書いたCoffeeScriptってのがなんか感慨深い。
gulp = require 'gulp' coffee = require 'gulp-coffee' plumber = require 'gulp-plumber' chalk = require 'chalk' notifier = require 'node-notifier' inspect = (require 'util').inspect path = require 'path' csSrc = './coffee/src/**/*.coffee' jsSrc = './script/src/**/*.js' dest = './dest' errorHandler = (err) -> title = '[ERROR:' + err.plugin + '] ' + err.name filename = path.relative(process.env.PWD, err.filename) console.log chalk.white.bgRed.bold title console.log err.toString() notifier.notify title: err.message, message: filename + '\n' + inspect(err.location), sound: 'Ping' gulp.task 'compile', -> gulp.src csSrc .pipe plumber(errorHandler: errorHandler) .pipe coffee( bare:true ) .pipe gulp.dest(dest) return gulp.task 'copy', -> gulp.src jsSrc .pipe gulp.dest(dest) gulp.task 'watch', ['copy', 'compile'], -> gulp.watch csSrc, ['compile'] gulp.watch jsSrc, ['copy'] gulp.task 'default', ['copy', 'compile']
$ gulp watch
で更新を監視させますが、変換エラーになったらデスクトップに通知させるようにしています。
なかなか便利。