ruby -- 进阶学习(十一)配置解决production环境下无法加载css或js

时间:2022-01-30 09:29:25

最近配置production环境,找了好几份文档,从傻逼到苦逼~~终于配置成功~~@_@!!!

首先,先加载以下几个插件:

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'# Use jquery as the JavaScript library
gem 'jquery-rails' gem 'execjs'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks' # Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'

接着修改config/environment/production.rb,部分代码如下:

  # Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true # Compress JavaScripts and CSS.
config.assets.compress = true
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false # Generate digests for assets URLs.
config.assets.digest = true

接着在config/application.rb中添加下面代码:

 1     config.assets.precompile << Proc.new do |path|
if path =~ /\.(css|js|scss|png|jpg|gif|json)\z/
full_path = Rails.application.assets.resolve(path).to_path
app_assets_path1 = Rails.root.join('app', 'assets').to_path
app_assets_path2 = Rails.root.join('public', 'assets').to_path
app_assets_path3 = Rails.root.join('vendor', 'assets').to_path if full_path.starts_with? app_assets_path1
true
else
if full_path.starts_with? app_assets_path2
true
else
if full_path.starts_with? app_assets_path3
true
else
false
end
end
end
end
end

如果有其他文件需要添加的,上面代码自行修改添加。

在app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

然后在开启服务器之前,在命令行输入 rake assets:precompile

Rails 会帮你把 assets 里的文件依照环境设定打包压缩放在 public/assets 目錄底下,所有的文件名称后会加入 MD5 的 fingerprinting 用來表示其內容供快取。

注:如果输入该命令行后发现无法加载css或js,或者是提示说.js文件已被加载,那么有可能是因为你的文件夹中还有别的application文件,里面的配置发生冲突。

接着开启服务器就可以了。。。

在配置过程中,由于存放在app/assets/images中的有些图片是被引用在css中的,而当你在命令行中运行了rake assets:percompile后,你会发现图片的文件名是被加密了,所以在css中无法找到图片,从而导致界面无法显示。

尝试过将图片路径进行修改,让它读取app/assets/images中的iphone.png,但是not working

会发现开启服务器后,在控制台那里可以看到读取不到图片的错误提示。而在public/assets中的图片由于文件名被加密,所以很难确定

后来由于自己很懒,就把要用到的图copy到public/assets中,上面贴的代码保持不变,然后就成功了。。。@_@|||

参考链接:

http://gogojimmy.net/2012/07/03/understand-assets-pipline/

http://ruby-china.org/topics/1415
http://ruby-china.org/topics/1414
http://ruby-china.org/topics/13216