【问题标题】:How can I run custom code before any asset precompile in Rails?如何在 Rails 中预编译任何资产之前运行自定义代码?
【发布时间】:2015-03-01 22:26:27
【问题描述】:

类似于(在初始化程序中):

Sprockets.before_precompile do
  # some custom stuff that preps or autogenerates some asset files
  # that should then be considered in the asset pipeline as if they were checked in
end

具体来说,我想运行一个 gulp 任务来将一些 Javascript 与一些特殊的预处理器捆绑在一起,我宁愿不重写我的 gulpfile 来让资产管道处理所有事情......我也希望这个工作如果可能的话,在 Heroku 上不需要自定义 buildpack。有什么想法吗?大概 Sprockets 有这些类型的钩子。

【问题讨论】:

    标签: ruby-on-rails heroku sprockets


    【解决方案1】:

    从源代码可以看出,Sprockets 没有这样的钩子,但你可以使用 rake 任务钩子。例如,您将创建一个启动所有预处理器、gulp 等的 rake 任务,因此该任务可以放在预编译之前。

    # lib/tasks/before_assets_precompile.rake
    
    task :before_assets_precompile do
      # run a command which starts your packaging
      system('gulp production')
    end
    
    # every time you execute 'rake assets:precompile'
    # run 'before_assets_precompile' first    
    Rake::Task['assets:precompile'].enhance ['before_assets_precompile']
    

    然后您只需运行rake assets:precompile,结果before_assets_precompile 任务将在它之前执行。

    还要确保使用system 而不是exec,因为exec 将在运行此预任务的阶段退出进程,并且不会按预期运行assets:precompile

    来源:

    1. Rake before task hook
    2. http://www.dan-manges.com/blog/modifying-rake-tasks

    【讨论】:

    • 正是我需要的!谢谢!
    • 这是否适用于development 模式下发生的自动资产编译?
    • @Suan,如果我没记错的话,开发环境的实时编译是在页面加载时完成的,每次重新加载页面时运行一个 gulp 任务来构建一个应用程序对我来说似乎有点矫枉过正。我想对于这种情况,最好使用 gulp watch,因此它只会在您更改源文件时构建应用程序,并且在页面重新加载时,您将获得 gulp 准备的最新资产。不过,我不确定是否有类似的 Rake 任务用于实时编译。
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2013-05-19
    • 1970-01-01
    • 2012-01-06
    相关资源
    最近更新 更多