Vagrant環境にLive Reloadを設定する
概要
LiveReload はファイルの変更を検知して、ブラウザを自動リロードするJavaScript製のライブラリ。 これを使うことで、cssやviewを修正したときに、手動でリロードせずに変更箇所を確認することができるようになる。
今回、Vagrantのゲスト内でRailsアプリケーションを動かしているので、これに対して、Live Reloadを設定する。
順番に書いていく。
Vagrantの設定変更
このとき、Live Reloadはデフォルトポートである35729番でListenするので、 ローカルホストの35729番へのアクセスをゲストへポートフォワードできるように設定する。
そのため、Vagrantfileには以下を追記して、読み込ませる。
private_ip = "192.168.13.37" config.vm.network(:private_network, :ip => private_ip) config.vm.network("forwarded_port", guest: 35729, host: 35729) #この一行を追記する。
そして
vagrant reload
ssh の設定変更
ローカルホストの35729 番へのアクセスを、プライベートIPの192.168.13.37の35729番にマッピングする。
$ ssh -L 35729:127.0.0.1:35729 vagrant@192.168.13.37
もしくは
sshのconfigを利用している場合は、次のように追記する。
Host 192.168.13.* Port 22 User vagrant IdentityFile /Users/togattti/.vagrant.d/insecure_private_key StrictHostKeyChecking no LocalForward 35729 192.168.13.37:35729 #この一行を、追記する。
ブラウザへの拡張プラグインのインストール
今回はGoogleChrome用のLive Reloadプラグインを入れた。
プラグインが有効になると、ブラウザの右上に専用のアイコンが追加される。
guard-livereloadをインストールする
guard-livereloadというruby製のライブラリを利用する。
Gemfileに追記して、bundle installする。
group :development do gem 'guard-livereload' end
その後、下記コマンドを実行する。
bundle exec guard init livereload
Guardfileという監視対象ファイルを管理するファイルが作られるので、 ホスト情報とポート番号を追記する。
# A sample Guardfile # More info at https://github.com/guard/guard#readme guard 'livereload', :host => '0.0.0.0', :port => '35729' do watch(%r{app/views/.+\.(erb|haml|slim)$}) watch(%r{app/helpers/.+\.rb}) watch(%r{public/.+\.(css|js|html)}) watch(%r{config/locales/.+\.yml}) # Rails Assets Pipeline watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html|png|jpg))).*}) { |m| "/assets/#{m[3]}" } end
guard-livereloadを動かしてみて、エラーが出ていなければ、大丈夫。
$ bundle exec guard -p -l 1 14:07:09 - INFO - Guard is using TerminalTitle to send notifications. 14:07:09 - INFO - Guard is now watching at '/home/vagrant/sample'
先ほどChromeに追加したプラグインを有効にしたときは、Browser connectedと記録される。
$ bundle exec guard -p -l 1 14:19:46 - INFO - Guard is using TerminalTitle to send notifications. 14:19:46 - INFO - Guard is now watching at '/home/vagrant/sample' 14:19:46 - INFO - LiveReload is waiting for a browser to connect. [1] guard(main)> 14:19:50 - INFO - Browser connected.
また、ファイルを変更したときは、ブラウザが自動でリロードされたことが記録される。
$ bundle exec guard -p -l 1 14:19:46 - INFO - Guard is using TerminalTitle to send notifications. 14:19:46 - INFO - Guard is now watching at '/home/vagrant/sample' 14:19:46 - INFO - LiveReload is waiting for a browser to connect. [1] guard(main)> 14:19:50 - INFO - Browser connected. 14:20:01 - INFO - Reloading browser: app/views/top/index.html.erb [1] guard(main)>
参考