How to minify CSS with Liquid
What I’ve been thinking about:
As developers, we are often taking on projects that have been previously built and require us to implement new functionality. One common issue I hear from most clients is their site is quite slow or scoring low on Google’s Lighthouse.
Whilst it would be great if we could always have complete control over how a theme has been built, it is not always possible to completely rewrite code and sometimes the budget a client has does not allow for much time to be spent improving and optimising their site.
I wanted to share one cool trick I found quite a while back. It uses Liquid to minify the CSS code, by removing unnecessary characters, comments, extra spaces and newlines. This helps to reduce the file size and improve the time it takes to fetch the stylesheet.
The Liquid code below can be used to wrap the client’s already existing CSS inside of the capture. It then strips and replaces parts of the CSS to minify it.
The Liquid code below can be added to the Liquid stylesheet, e.g. theme.scss.liquid. The already existing css should be wrapped inside of the capture. The CSS will then be formatted to strip and replace specific parts to create the newly minified version.
Credit goes to Tim on the Shopify Community Forum where I originally found this code https://community.shopify.com/c/technical-q-a/tool-to-minify-css-liquid/m-p/1123337
3 links you can’t miss:
- Free icons I’m always spending time searching for icons for clients and this site definitely helps reduce that time since it has a huge library of free icons
- Shopify Theme Console Shopify CLI now has REPL (read-eval-print loop) tool for testing out Liquid, it’s very cool to see that they have implemented this and I’m sure many will find it very helpful
- RunJS App I’ve also recently found RunJS which is a very nice way to play around and test out new ideas in a JavaScript environment. Of course you could just use Node.JS or an online tool like JSFiddle, but they definitely don’t look as nice
One app I like:
I have used quite a few different apps to power search and collection pages in the past, whether this be restyling the pre-built options or even building them completely from scratch. Recently, I have been using Algolia to power a new collection page that I am working on and it has definitely been one of the nicest experiences. I’m currently building a new site with Vue and the Algolia Vue components they provide have made the whole experience very simple. It provides you with pre-built components that you can also override using Vue Slots.
The app might not be for every client because of it’s cost but I definitely have enjoyed building with Algolia and would love to work on more projects in the future that use it.