all repos — homestead @ bbc078fe337b6d3f0e17b5c0c2bc429ed5262504

Code for my website

Purge CSS using npm:purgecss

Alan Pearce
commit

bbc078fe337b6d3f0e17b5c0c2bc429ed5262504

parent

3ef8367f2bb3ea58d405e49b6ee2fae5d807736f

1 file changed, 34 insertions(+), 3 deletions(-)

jump to
M cmd/build/main.gocmd/build/main.go
@@ -2,6 +2,7 @@ package main
import ( "bytes" + "encoding/json" "encoding/xml" "fmt" "io/fs"
@@ -9,6 +10,7 @@ "log"
"log/slog" "net/url" "os" + "os/exec" "path" "path/filepath" "slices"
@@ -120,15 +122,44 @@ })
return posts, tags, nil } +type purgeCSSOutput struct { + CSS string `json:"css"` + File string +} + +var purgedCSS map[string]string + +func purgeCSS(htmlFilename string, cssFilename string) (string, error) { + if purgedCSS == nil { + purgedCSS = make(map[string]string) + } else if purgedCSS[htmlFilename] == "" { + bytes, err := exec.Command("bun", "./node_modules/.bin/purgecss", "--css", cssFilename, "--content", htmlFilename).Output() + if err != nil { + return "", errors.WithMessage(err, "failed running `purgecss` command") + } + var out []purgeCSSOutput + err = json.Unmarshal(bytes, &out) + if err != nil { + return "", errors.WithMessage(err, "failed decoding `purgecss` output") + } + purgedCSS[htmlFilename] = out[0].CSS + } + return purgedCSS[htmlFilename], nil +} + func layout(filename string, config Config, pageTitle string) (*goquery.Document, error) { html, err := os.Open(filename) if err != nil { return nil, err } defer html.Close() - css, err := os.ReadFile("templates/style.css") + css, err := purgeCSS(filename, "templates/style.css") if err != nil { - return nil, err + bytes, err := os.ReadFile("templates/style.css") + if err != nil { + return nil, err + } + css = string(bytes) } doc, err := goquery.NewDocumentFromReader(html) if err != nil {
@@ -138,7 +169,7 @@ doc.Find("html").SetAttr("lang", config.DefaultLanguage)
doc.Find("head > link[rel=alternate]").SetAttr("title", config.Title) doc.Find(".title").SetText(config.Title) doc.Find("title").Add(".p-name").SetText(pageTitle) - doc.Find("head > style").SetHtml(string(css)) + doc.Find("head > style").SetHtml("\n" + string(css)) nav := doc.Find("nav") navLink := doc.Find("nav a") nav.Empty()