How can I minify a css.liquid file without using Shopify's deprecated sass?

I use this code to minify CSS+liquid code – it simply wraps the contents of you file:

{%- capture content %}

	... contents of your CSS+Liquid file here ...

/* homebrew CSS minifier */

{%- endcapture -%}
{%- assign before =  content.size -%}
{%- assign content =  content | strip_newlines | split: " " | join: " " | split: "*/" -%}
{%- assign new_content = "" -%}
{%- for word in content -%}
	{%- assign new_word = word | split: "/*" | first | strip | replace: "; ", ";" | replace: "} ", "}" | replace: "{ ", "{" | replace: " {", "{" -%}
  	{%- assign new_content = new_content | append: new_word -%}
{%- endfor -%}
/* CSS minifed: {{ before }} --> {{ new_content.size }} */
{{- new_content  }}

Works good enough for Google PageSpeed/Lighthouse. Basically – removes comments, extra spaces and newlines…

5 Likes