原因是這樣,有一個新的項目,前端想要加入livereload,但沒搭建成功。另一後端又沒搭過,覺得他搭的話,會花費一些時間,索性我我就把它搭了起來。
livereload這種雖然搭建起來沒什麼難度,但要重頭做要看很多東西,比較浪費時間,所以寫了這個類似教程的東西,以便節省時間。
簡介
livereload配合guard,可以達到改動html,assets文件時,刷新頁面的效果(如果改動的是css,樣式會自動重新加載),可以説是前端開發的必備工具之一。
1. 加入Gems
# Guard is a command line tool to easily handle events on file system modifications.
# https://github.com/guard/guard
gem 'guard'
# Guard::LiveReload automatically reload your browser when 'view' files are modified.
# https://github.com/guard/guard-livereload
gem 'guard-livereload'
# Bring in livereload.js into handy Rack middleware.
# https://github.com/johnbintz/rack-livereload
gem 'rack-livereload'
2. 編輯Guardfile
- 生成Guardfile
bundle exec guard init - 配置livereload,在Guardfile寫入如下代碼
guard 'livereload' do
extensions = {
css: :css,
scss: :css,
sass: :css,
js: :js,
coffee: :js,
html: :html,
png: :png,
gif: :gif,
jpg: :jpg,
jpeg: :jpeg,
# less: :less, # uncomment if you want LESS stylesheets done in browser
}
rails_view_exts = %w(erb haml slim)
# file types LiveReload may optimize refresh for
compiled_exts = extensions.values.uniq
watch(%r{public/.+\.(#{compiled_exts * '|'})})
extensions.each do |ext, type|
watch(%r{
(?:app|vendor)
(?:/assets/\w+/(?<path>[^.]+) # path+base without extension
(?<ext>\.#{ext})) # matching extension (must be first encountered)
(?:\.\w+|$) # other extensions
}x) do |m|
path = m[1]
"/assets/#{path}.#{type}"
end
end
# file needing a full reload of the page anyway
watch(%r{app/views/.+\.(#{rails_view_exts * '|'})$})
watch(%r{app/helpers/.+\.rb})
watch(%r{app/controllers/.+\.rb})
watch(%r{config/locales/.+\.yml})
end
配置 livereload for development env
在config/environments/development.rb加入
# Add Rack::LiveReload to the bottom of the middleware stack with the default options:
config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload
最後測試,打完收工。
References
- guard
- guard-livereload
- rack-livereload