如何在Ruby on Rails中压缩HTML输出?

3
我有一个基于Ruby on Rails的应用程序,使用HAML来构建HTML结构。我想要对输出的“html”进行压缩/混淆,移除不必要的空格和换行符。类似于这样:
<div class='wrapper v2-header-wrapper' id='fix-content'><div class='header header-search' style='text-align: center !important;'><nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand-lg'><button class='navbar-toggler navbar-toggler-right' onclick='openNav()' type='button'><span class='navbar-toggler-icon'><i class='fa fa-bars'></i></span></button><a class='navbar-brand mobile pull-left' href='/'><i class='fa fa-search'></i>

不要这样做:

<div class='wrapper v2-header-wrapper' id='fix-content'>
<div class='header header-search' style='text-align: center !important;'>
<nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand- 
lg'>
<button class='navbar-toggler navbar-toggler-right' onclick='openNav()' 
type='button'>
<span class='navbar-toggler-icon'>
<i class='fa fa-bars'></i>
</span>
</button>
<a class='navbar-brand mobile pull-left' href='/'>
<i class='fa fa-search'></i>

非常感谢您的帮助,非常感谢。

事先表示感谢。


1
我不会担心缩小你的HTML。如果你想优化页面的加载速度,我会在其他地方寻找解决方法。 - Adam H
1
我觉得你想要的是对响应进行压缩。在这里看一下 Simon F 的回答: https://dev59.com/t18e5IYBdhLWcg3wnbRj#25576573 - Simon Franzen
@SimonFranzen 我实际上尝试了那个答案,但那不是我要找的。 - 4 R4C81D
1
也许我没有理解“为什么”的原因。 - Simon Franzen
链接的答案解释了如何压缩,而不是如何缩小HTML。 - kaikuchn
1
我也在寻找一个HTML缩小器,因为我想在gzip之前减少编译后静态HTML页面的大小。有https://code.google.com/archive/p/htmlcompressor/,但没有为其维护Ruby绑定。 - kaikuchn
2个回答

2

试试这个:

app/middleware/html_minifier.rb

class HtmlMinifier
  def initialize(app)
    @app = app
  end

  def call(env)

    # Call the underlying application, return a standard Rack response
    status, headers, response = @app.call(env)

    # Make sure we don't process CSS or JavaScript
    if headers["Content-Type"] =~ /text\/html/
      response.each do |chunk|
        [
          # Join lines
          [/[\r\n]+/, ""],

          # Remove whitespace between tags
          [/>\s+</, "><"],

          # Remove comments
          [/<!--(.|\s)*?-->/, ""],

          # Remove whitespace in inline JavaScript
          [/;\s+/, ";"],
          [/{\s+/, "{"]
        ].each do |regex, substitute|
          chunk.gsub! regex, substitute
        end
      end
    end

    # Return the new Rack response
    [status, headers, response]
  end
end

1

有一个Gem可以解决这个问题。只需将以下内容添加到Gemfile文件中:

gem 'htmlcompressor', '~> 0.4.0'

并将以下内容添加到你的application.rb文件中:

config.middleware.use HtmlCompressor::Rack

我正在一个Rails 6应用程序中使用它,它可以直接使用。我还建议启用GZip压缩。您可以使用此中间件完成:

config.middleware.use Rack::Deflater 

最后一个中间件不需要外部 Gem。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接