缺少gzip版本的css和js资产

我正在使用Rails 4.2进行一个非常简单的项目。 当我运行rake assets:precompile (用于开发和生产环境)时,我在public / assets中获得了application-xyz.jsapplication-xyz.css文件。 但是没有创建gzip版本,即没有application-xyz.js.gz ,也没有application-xyz.css.gz 。 我不知道有任何禁用此function的选项。 我错过了什么吗?

链轮3不再生成gzip压缩版本的资产。 根据这个问题 ,很大程度上是因为它们很少被实际使用。

您可以通过在预编译后自己gzipping资产来恢复此function,例如Xavier Noria的示例capistrano任务使用find迭代assets文件夹中的所有css和js文件,然后使用xargs将它们传递给gzip

 namespace :deploy do # It is important that we execute this after :normalize_assets because # ngx_http_gzip_static_module recommends that compressed and uncompressed # variants have the same mtime. Note that gzip(1) sets the mtime of the # compressed file after the original one automatically. after :normalize_assets, :gzip_assets do on release_roles(fetch(:assets_roles)) do assets_path = release_path.join('public', fetch(:assets_prefix)) within assets_path do execute :find, ". \\( -name '*.js' -o -name '*.css' \\) -exec test ! -e {}.gz \\; -print0 | xargs -r -P8 -0 gzip --keep --best --quiet" end end end end 

我更喜欢

 namespace :assets do desc "Create .gz versions of assets" task :gzip => :environment do zip_types = /\.(?:css|html|js|otf|svg|txt|xml)$/ public_assets = File.join( Rails.root, "public", Rails.application.config.assets.prefix) Dir["#{public_assets}/**/*"].each do |f| next unless f =~ zip_types mtime = File.mtime(f) gz_file = "#{f}.gz" next if File.exist?(gz_file) && File.mtime(gz_file) >= mtime File.open(gz_file, "wb") do |dest| gz = Zlib::GzipWriter.new(dest, Zlib::BEST_COMPRESSION) gz.mtime = mtime.to_i IO.copy_stream(open(f), gz) gz.close end File.utime(mtime, mtime, gz_file) end end # Hook into existing assets:precompile task Rake::Task["assets:precompile"].enhance do Rake::Task["assets:gzip"].invoke end end 

资源

从Sprockets 3.5.2开始,再次启用gzip压缩并生成gz资产。 您必须配置服务器才能正确提供服务。 对于Nginx:

 location ~ ^/(assets)/ { gzip_static on; } 

然后在application.rb中:

  config.middleware.insert_before(Rack::Sendfile, Rack::Deflater) # Compress JavaScripts and CSS. config.assets.compress = true config.assets.js_compressor = Uglifier.new(mangle: false)