自作npmをcoffeeで書いた時compileはどこでするか

インストール時のお話。

何をcoffeeで書いたとしても吐かれたjsはあまり見たくないわけですが、ましてやバージョン管理なんてもっての外だし当然配布時もjsファイルは含めたくない、って時にどうするか。

https://www.npmjs.org/doc/misc/npm-scripts.html

npmのドキュメントのscriptsの項を見ます。
ここにはpackage.jsonのscriptsの項が何かということが書いてあるわけなんですが、scriptsはいわゆるhookスクリプトみたいなものです。
npmモジュールが動作する各時点において指定したコマンドを実行してくれます。

prepublish: Run BEFORE the package is published. (Also run on local npm install without any arguments.)
publish, postpublish: Run AFTER the package is published.
preinstall: Run BEFORE the package is installed
install, postinstall: Run AFTER the package is installed.
preuninstall, uninstall: Run BEFORE the package is uninstalled.
postuninstall: Run AFTER the package is uninstalled.
preupdate: Run BEFORE the package is updated with the update command.
update, postupdate: Run AFTER the package is updated with the update command.
pretest, test, posttest: Run by the npm test command.
prestop, stop, poststop: Run by the npm stop command.
prestart, start, poststart: Run by the npm start command.
prerestart, restart, postrestart: Run by the npm restart command. Note: npm restart will run the stop and start scripts if no restart script is provided.

指定できるのは上記のもの。丁寧に時系列順で書かれています。各scriptsがそれぞれどの時点でhookされるかはここでは解説しませんが、今回利用するのはinstallです。
自作モジュールが実行される以前にcoffee compileを(一度だけ)済ませる必要があるのでこの時点となります。

installは「Run AFTER the package is installed.」と書かれている通り、npm installが済んだ時点でhookされます。でもそれより前の時点でhookされるものとしてprepublishやらpublishやらあるけどつまりいつよ?となるわけですが、installは分かりやすいです。mainファイル等のコピーが済んでpackage.jsonに書いてある依存モジュールがinstallされた時点でhookされます。というかそのあとが「preuninstall」とかなんで分かると思いますが、すべての配置が済んで利用可能な状態になった時ですね。(coffee compileが済んでないので利用可能な状態じゃないんですが)

利用されるより前にcoffee compileできればいいんだからpublishやpreinstallでもいいのでは?と思うかもしれません。が、そこでやってしまうとcoffee自体が存在しない場合にcompileできないためやはりnpm installが済んだ後であるinstallでやる必要があります。もちろん依存モジュールにcoffeeを含めることを忘れずに。

ということでcoffee compileをしてやるところが分かったのでpackage.jsonに記述します。

"scripts": {
    "install": "coffee -bco output/ input/"
},
"dependencies": {
    "coffee-script": "^1.7.1"
}


今までscriptsをよく知らずtestしか使ったことなかったんですが、jsファイルを除去する方法を調べていてscriptsが使えそうってことで調べ直す機会ができたのでメモがてらのエントリーでした。

もしかしたらbinでcoffeeコマンド叩いてやればcoffee compileすら必要ないのかもしれないんですが、カレントディレクトリがずれてしまってうまくいかなかったのでやり方知っている方いたら教えてください…。

追記

真面目に書いてない時は index.jsに require('coffee-script/register'); require('src/main') みたいな感じに書いてる

coffee-script/registerを利用するとjsからcoffeeをrequireできます。なるほど、これならcoffee compileを介す必要はありませんね。
今回自分が書いていたのはコマンドラインのものだから

  "bin": {
    "hoge": "./index.js"
  }
#!/usr/bin/env node
require("coffee-script/register");
require("./src/main");

こんな感じかな。/usr/bin/env coffeeでcoffee実行するようにしてもいいのかも。
package.jsonでmainに指定するものならコメントの通りワンライナーのjsでよさそうです。
id:mizchi ありがとうございます。