Skip to content

Instantly share code, notes, and snippets.

@ajchemist
Forked from mhuebert/_.md
Created December 26, 2020 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajchemist/bfbe1f3876bc1ab227dfc5819c070911 to your computer and use it in GitHub Desktop.
Save ajchemist/bfbe1f3876bc1ab227dfc5819c070911 to your computer and use it in GitHub Desktop.
shadow-cljs build hook for purgecss

purgecss is a tool for removing unused css classes from source files. It's particularly useful for functional css frameworks like tachyons, where it's normal to only use a tiny fraction of available classes. This gist contains example code you could use to add purgecss to a shadow-cljs build.

  • make sure to yarn add purgecss first
  • usage is (hooks/purge-css {:css-source __ :js-globs __ :out-dir __})
    • :css-source is the path to the original, bloated CSS file (from project root). This is ideally in a source directory, or node_modules as in this example. This cannot be the public path where the css is ultimately read.
    • :js-globs is a string / vector of strings, indicating which files to read as input. These should be all of your compiled javascript bundles which contain your views. purgecss does a brute-force parse of all these files, extracting all the strings to figure out which classnames are definitely not used.
    • :public-dir is the public directory where you want the purged CSS file to be written (it will have the same name as the original).

In dev mode, the source CSS file is simply copied to the :public-dir. In release mode, only classes used by your build are included.

(ns hooks
(:require [clojure.java.shell :refer [sh]]
[clojure.string :as str]))
(defn exec [& cmd]
(let [cmd (str/split (str/join " " (flatten cmd)) #"\s+")
_ (println (str/join " " cmd))
{:keys [exit out err]} (apply sh cmd)]
(if (zero? exit)
(when-not (str/blank? out)
(println out))
(println err))))
(defn purge-css
{:shadow.build/stage :flush}
[state {:keys [css-source
js-globs
public-dir]}]
(case (:shadow.build/mode state)
:release
(exec "purgecss --css " css-source
(for [content (if (string? js-globs) [js-globs] js-globs)]
(str "--content " content))
"--out" public-dir)
:dev
(do
(exec "mkdir -p" public-dir)
(exec "cp" css-source (str public-dir "/" (last (str/split css-source #"/"))))))
state)
{...
:builds
{:browser
{...
:build-hooks [(hooks/purge-css
{:css-source "node_modules/tachyons/css/tachyons.min.css"
:js-globs ["public/build/*.js"]
:public-dir "public/build"})]}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment