很多时候,Web开发人员都希望自己修改完的CSS代码后,可以立刻生效,看到结果。而不是需要开发人员再次刷新页面才可以看到更新的效果。


如果你也是这样想的,我想你可以继续往下看!

guard-livereload

可以轻松的帮助我们实现此功能。


*. 我们需要在Gemfile中引入对应的gems
group :development do
  gem 'guard-livereload', require: false
  gem "rack-livereload"
end
*. 然后为你的项目生成对应的配置文件, 请运行如下命令在Project根目录
guard init livereload
* 会在根目录生成一个Guardfile(因为我们只想在开发环境使用, 如果您使用git, 我们需要配置忽略此文件)
cat 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+base without extension
           (?\.#{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{config/locales/.+\.yml})
end
*. 需要创建一个web socket用户和前台通信的配置, 添加如下配置到你的config/development.rb中
Rails.application.configure do
  # Add Rack::LiveReload to the bottom of the middleware stack with the default options:
  config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload
end
*. 我们启动一个后台实时监听的脚本
$ bundle exec guard
09:01:38 - INFO - Guard is now watching at 
09:01:38 - INFO - LiveReload is waiting for a browser to connect.
[1] guard(main)> 09:03:40 - INFO - Browser connected.

*. 打开浏览器,然后开始你的旅途吧。