Gruntでlivereloadをする

Gruntでlivereload出来るらしかったので、試してみました。
jadeとstylusのファイルを監視してもらって、変更したらコンパイルとlivereloadでの更新をしてもらうという感じです。

package.json
...
  "scripts": {
    "postinstall": "bower install && grunt bower:install",
    "start": "grunt"
  },
  "devDependencies": {
    "bower": "~1.2",
    "grunt": "~0.4",
    "grunt-cli": "~0.1",
    "grunt-bower-task": "~0.3",
    "grunt-contrib-connect": "~0.5",
    "grunt-contrib-jade": "~0.8",
    "grunt-contrib-stylus": "~0.8",
    "grunt-contrib-watch": "~0.5"
  }
...

こんな感じで書いておきます。
grunt-bower-taskでライブラリの位置を移動する必要が無い場合はモジュールと、postinstallの&&以降が要らないです。
grunt-contrib-livereloadが必要、と書いてあるページもあったのだけどインストールしてみたらdeprecateだよ〜watchに統合したよ〜みたいなことが書いてって、watchだけでいいみたい。

Gruntfile.coffee
module.exports = (grunt) ->

  grunt.initConfig
    bower:
      install:
        options:
          cleanup: true
          install: true
          layout: (type, component) -> '..' # project root dir
    connect:
      server:
        options:
          port: 3000
          base: '.'
    jade:
      compile:
        files:
          'index.html': ['jade/*.jade']
    stylus:
      compile:
        files:
          'index.css': ['styl/*.styl']
    watch:
      options:
        livereload: true
      jade:
        files: 'jade/*.jade'
        tasks: 'jade'
      stylus:
        files: 'styl/*.styl'
        tasks: 'stylus'

  grunt.loadNpmTasks 'grunt-bower-task'
  grunt.loadNpmTasks 'grunt-contrib-connect'
  grunt.loadNpmTasks 'grunt-contrib-jade'
  grunt.loadNpmTasks 'grunt-contrib-stylus'
  grunt.loadNpmTasks 'grunt-contrib-watch'

  grunt.registerTask 'default', ['connect', 'jade', 'stylus', 'watch']

  return

connectとwatch便利だね。

jade/index.jade
script(src="//localhost:35729/livereload.js")

jadeのファイルのどこかに上記を入れておく必要があります。
これもgruntなんちゃらを使えば、開発中だけ埋め込むとかできると思うんだけど、まだ調べてない。

使う

$ npm install
$ npm start

これでライブラリのインストールと監視は完了。
あとは好きなように編集すればブラウザが勝手に再読み込みされるよ!


参考:
http://www.slideshare.net/sakunyo/jscafe-v
http://qiita.com/mizchi/items/1d10874dc0956d30fd92


追記:
せっかくjadeなので以下のようにしました。

jade/index.jade
doctype 5
html
  head
    ...
  body
    ...
    include _livereload
jade/_livereload.jade
if process.env.NODE_ENV !== 'build'
  script(src="//localhost:35729/livereload.js")


これで、ビルドするときに気をつけてNODE_ENVにbuildを指定してコンパイルすればlivereloadのコードが含まれない形でjadeがコンパイルされるので、普段の開発時はlivereloadが効いて良いのではないかなーと思います。