在Rails 4中,如何让Rake任务缩小我的资产?

时间:2017-03-16 17:18:46

标签: ruby-on-rails-4 rake asset-pipeline

我需要将我的资产子集导出到某些外部网站。我已经创建了一个rake任务:

<iron-image style$="width: {{imgWidth}}px; height:{{imgWidth}}px" ...></iron-image>
<iron-image style$="width: {{imgWidth}}px; height:{{imgWidth}}px" ...></iron-image>  
<iron-image style$="width: {{imgWidth}}px; height:{{imgWidth}}px" ...></iron-image>

问题是我无法让资产库缩小我的库。这是我的任务方法中的代码:

rake build:navbar

它会生成我的资产的压缩版本(desc "Build navbar assets and markup for other sites." task navbar: :environment do # Set environment to production so pipeline will minify assets. Rails.env = "production" # Some setup code removed... # How do we coax assets into minifying files? Rails.application.config.assets.prefix = "../build/navbar/staging" Rails.application.config.assets.js_compressor = :uglifier Rails.application.config.assets.css_compressor = :sass Rails.application.config.assets.digest = false Rails.application.config.assets.compress = true Rails.application.config.assets.debug = false Rails.application.config.assets.paths = [Rails.root.join('/app/assets/javascripts'), Rails.root.join('/app/assets/stylesheets/navbar')] Rails.application.config.assets.precompile = ['navbar.js', 'navbar.css'] # Compile now. Rake::Task['assets:clean'].invoke Rake::Task['assets:precompile'].invoke # Cleanup code removed... end ),但不会生成缩小版本(navbar.css.gz)。

我上下搜索了这个设置配方应该可以解决这个问题。我错过了什么?

1 个答案:

答案 0 :(得分:0)

我想我已经确定了潜在的问题。资产管道任务,即sprockets-rails,并不完全尊重配置设置。它似乎覆盖了一些设置,具体取决于Rails环境。而且你不能简单地change the Rails environment within a rake task

目标再次是使用此rake命令将Rails应用程序资产的子集移植到另一个项目:

rake build:navbar

以下是一些示例代码,展示了我如何解决这些问题:

namespace :build do
  desc "Build navbar assets and markup."
  task navbar: :environment do
    # Prep Builder
    builder = Navbar::Builder.new(target: target)
    builder.prep_build

    # Why this? Setting Rails.env or ENV['RAILS_ENV'] didn't work.
    system("rake build:navbar_assets RAILS_ENV=production")

    builder.generate_markup_file
    builder.move_output_files_to_build_directory
    builder.cleanup
  end

  desc "Build navbar assets."
  task navbar_assets: :environment do
    # Configure the asset pipeline to compile minified files.
    # NOTE: Sprockets only minifies files in production environment (or won't
    # do it in development) so this assumes RAILS_ENV is set to production
    # on the command line.
    Rails.application.config.assets.prefix = "../build/navbar/staging"
    Rails.application.config.assets.paths = [Rails.root.join('app/assets/javascripts'),
                                             Rails.root.join('app/assets/stylesheets')]
    Rails.application.config.assets.precompile += ['navbar.js', 'navbar.css']

    # Let it rip.
    Rake::Task['assets:clobber'].invoke
    Rake::Task['assets:precompile'].invoke
  end
end

在问题的代码中,文件路径构建也存在一些问题。那些已被纠正。