rails生产环境css无法加载问题

此文为全部转载,http://www.makaidong.com/%E5%8D%9A%E5%AE%A2%E5%9B%AD%E6%96%87/30104.shtml

rails 4.0 -- production环境配置之解决无法加载css或js
最近配置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|
2       if path =~ /\.(css|js |scss|png|jpg|gif|js on)\z/
3         full_path = rails.application.assets.resolve(path).to_path
4         app_assets_path1 = rails.root.join('app', 'assets').to_path
5         app_assets_path2 = rails.root.join('public', 'assets').to_path
6         app_assets_path3 = rails.root.join('vendor', 'assets').to_path
7
8         if full_path.starts_with? app_assets_path1
9           true
10         else
11           if full_path.starts_with? app_assets_path2
12             true
13           else
14             if full_path.starts_with? app_assets_path3
15               true
16             else
17               false
18             end
19           end
20         end
21       end
22     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中,上面贴的代码保持不变,然后就成功了。。。@_@|||

猜你喜欢

转载自hhg08.iteye.com/blog/2306280