Lightweight CSS minifier

2022-07-13

There are many styles compression libraries. But their functionality is too redundant for a small application. The main part with the removal of whitespace characters can fit in a couple of lines of code:

style_file_name = 'public/css/style.css'
min_file_name = style_file_name.gsub(/\.css$/, '.min.css')

File.open(style_file_name, 'r') do |style_file|
  File.open(min_file_name, 'w') do |min_file|
    min_file.write(
      style_file
        .readlines
        .map(&:strip)
        .join
        .gsub(' > ', '>')
        .gsub(' {', '{')
        .gsub(': ', ':')
        .gsub(', ', ',')
        .gsub(';}', '}')
    )
  end
end

In my case I've created a rake task which is then run by Capistrano at the end of the deployment process.

To use the minified file in production, don't forget to change the <link> tag in the <head>

<link rel="stylesheet" href="<%= Sinatra::Application.production? ? '/css/style.min.css' : '/css/style.css' %>">