如何加快Rails Asset Pipeline预编译过程?

xdi*_*ite 62 ruby-on-rails asset-pipeline

有什么方法可以加快Rails Asset Pipeline预编译过程?

xdi*_*ite 79

1. Capistrano部署加速

(1)使用capistrano内置任务'deploy/assets'进行部署.

Capistrano有自己的内置任务'部署/资产'.它会自动为您完成任务.

您自己的手工任务之间的区别在于它只加载assets组来预编译资产,而不是整个环境.

cd /home/apps/APP_NAME/releases/20120708184757 && bundle exec rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile

(2)在资产未更改时跳过预编译过程.

https://gist.github.com/3072362

如果

  • 应用程序/资产
  • LIB /资产
  • 供应商/资产
  • Gemfile.lock的
  • confir/routes.rb中

如果改变了,它将重新编译资产.否则,它将跳过pecompile进程,节省大量时间.

2.仔细使用@import.

(1)避免@import "compass";直接使用.

它会同时适用于你

@import "compass";@import "compass/typography/links/link-colors";在SCSS中.

但是@import "compass/typography/links/link-colors";@import "compass";编译资产快9倍.

那是因为什么时候@import "compass";,它编译整个罗盘资产.不仅仅是link-colors一部分.

(2)避免使用局部

在SCSS中,我们喜欢partial用来组织我们的资产.

但是,只有当您需要共享变量或者存在必要的依赖关系时,否则

//= require "reset"
//= require "base"
//= require "product"
Run Code Online (Sandbox Code Playgroud)

比...更快

@import "reset";
@import "base";
@import "product";
Run Code Online (Sandbox Code Playgroud)

3.不要无理由地要求.scss和.coffee

(1)避免使用require_tree

当我们使用Rails生成器生成控制器时.Rails也会生成这样的资产

  • product.css.scss
  • product.js.coffee

使用以下技术在application.js中挂载资产:

//= require_tree
Run Code Online (Sandbox Code Playgroud)

但空的资产(没有输出)只包含这一行:

# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
Run Code Online (Sandbox Code Playgroud)

编译它们将耗费大约250ms.如果您有10个空资产,则为2.5秒.

从项目中删除它们,或者在application.js中单独安装它们,如下所示:

//= require prodcuts
//= require users
//= require albums
Run Code Online (Sandbox Code Playgroud)

(2)不要使用css.scssjs.coffee不必要.

  • 编译jquery-ui-1.8.16.custom.css(0ms)(pid 19108)
  • 编译jquery.ui.1.8.16.ie.css(0ms)(pid 19108)
  • 编译jquery.js(5ms)(pid 19108)
  • 编译jquery_ujs.js(0ms)(pid 19108)
  • 编译custom.css(14ms)(pid 19108)

custom.csscustom.css.scss

编译纯CSS和纯JS很快(成本几乎为0毫秒).但是编译.scss和.coffee仍需花费一些时间.

总结

  1. 替换deploy.rb资产任务.
  2. 检查日志/ production.log

    • 找到缓慢的资产
    • 删除@import"指南针"; 使用替代解决方案
    • 使用require代替@import; (当真的有必要时使用@import)
    • 删除require_tree,单独挂载资产
    • 删除空的.scss和.coffeescript
    • 当资产是纯CSS时使用.css.


ndb*_*ent 20

我刚刚编写了一个gem来解决Rails中的这个问题,称为turbo-sprockets-rails3.它assets:precompile通过仅重新编译已更改的文件来加速您的速度,并且仅编译一次以生成所有资产.

请注意,我也试图将此补丁合并到Rails 4.0.0,可能还有Rails 3.2.9(参见https://github.com/rails/sprockets-rails/pull/21).但是现在,如果你可以帮我测试一下turbo-sprockets-rails3宝石会很棒,如果你有任何问题请告诉我.

  • @brauliobo,Rails 4有一些独立的资产改进,这意味着你不再需要使用这个gem了. (2认同)