简体   繁体   English

在response_to javascript响应上使用Rails Javascript压缩/最小化?

[英]Rails Javascript compression/minification on respond_to javascript response?

Greetings Rails and Javascript Gurus! 问候Rails和Javascript大师!

I have a project where I am returning a large javascript file in a 我有一个项目,我在其中返回一个大的javascript文件

respond_to do |format|
   format.js
end

block. 块。

I am trying to figure out how I can minify or compress the .js response since the .js.erb view is full of comments and varies in size based on the results from the controller. 我正在尝试弄清楚如何缩小或压缩.js响应,因为.js.erb视图中充满了注释,并且根据控制器的结果大小有所不同。

Anyone have any ideas? 有人有想法么?

对于Rails 4:

render js: Uglifier.new.compile(render_to_string)

well, maybe I have a solution: 好吧,也许我有一个解决方案:

respond_to do |format|
  format.js { self.response_body = minify(render_to_string) }
end

This perfectly works. 这完美地工作。 Of course that the key is the minify method. 当然,关键是缩小方法。 You will find a lot of JS minifiers around. 您会发现周围有很多JS缩小器。 For example you can use this one (well if license permits): http://github.com/thumblemonks/smurf/raw/master/lib/smurf/javascript.rb - it is based on Crockford's jsmin.c. 例如,您可以使用此代码(如果许可证允许的话): http ://github.com/thumblemonks/smurf/raw/master/lib/smurf/javascript.rb-它基于Crockford的jsmin.c。

If you put this file into your lib, require it, your minify method can look like this: 如果将此文件放到您的lib中,则需要它,您的minify方法如下所示:

def minify(content)
  min = Smurf::Javascript.new(content)
  min.minified
end

Hope that it helped you. 希望对您有所帮助。

If you plan to do minifying automatically then you probably should go for a piece of middleware. 如果您打算自动缩小,那么您可能应该选择一块中间件。 Surprisingly I was not able to find any (there are many aimed to the CSS/JS but it's about static assets not dynamic content) but it would not be such a problem to write it. 出乎意料的是,我找不到任何东西(有很多针对CSS / JS的东西,但这是关于静态资产而不是动态内容的),但是编写它并不是问题。

For rails 3 using the built in Uglifier method (the default for the assets pipeline) 对于使用内置Uglifier方法的rails 3(资产管道的默认设置)

See Radek's code above and just swap this in. 参见上面的Radek的代码,然后将其交换。

  def minify(content)
    Uglifier.new.compile(content)
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM