Skip to content

Commit 200af09

Browse files
authored
cli/serve: Fix unocss HMR (#1091)
1 parent 4716bdf commit 200af09

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

cli/dev_server.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,8 @@ func (d *DevServer) ServeHtml(w http.ResponseWriter, r *http.Request, pathname s
202202
defer htmlFile.Close()
203203

204204
tokenizer := html.NewTokenizer(htmlFile)
205-
unocss := ""
206205
cssLinks := []string{}
206+
unocss := ""
207207
overriding := ""
208208

209209
for {
@@ -242,9 +242,13 @@ func (d *DevServer) ServeHtml(w http.ResponseWriter, r *http.Request, pathname s
242242
if srcUrl, parseErr := url.Parse(srcAttr); parseErr == nil && srcUrl.Path == "/x" {
243243
hrefAttr, _ = utils.SplitByFirstByte(hrefAttr, '?')
244244
if hrefAttr == "uno.css" || strings.HasSuffix(hrefAttr, "/uno.css") {
245-
w.Write([]byte("<link rel=\"stylesheet\" href=\""))
246-
w.Write([]byte(hrefAttr + "?ctx=" + base64.RawURLEncoding.EncodeToString([]byte(pathname))))
247-
w.Write([]byte{'"', '>'})
245+
if unocss == "" {
246+
unocssHref := hrefAttr + "?ctx=" + base64.RawURLEncoding.EncodeToString([]byte(pathname))
247+
w.Write([]byte("<link rel=\"stylesheet\" href=\""))
248+
w.Write([]byte(unocssHref))
249+
w.Write([]byte{'"', '>'})
250+
unocss = unocssHref
251+
}
248252
overriding = "script"
249253
} else {
250254
w.Write([]byte("<script type=\"module\""))
@@ -294,7 +298,7 @@ func (d *DevServer) ServeHtml(w http.ResponseWriter, r *http.Request, pathname s
294298
}
295299
// reload the unocss when the module dependency tree is changed
296300
if unocss != "" {
297-
fmt.Fprintf(w, `hot.watch("*",(kind,filename)=>{if(/\.(js|mjs|jsx|ts|mts|tsx|vue|svelte)$/i.test(filename)){document.getElementById("@unocss").href="%s&t="+Date.now().toString(36)}});`, unocss)
301+
fmt.Fprintf(w, `hot.watch("*",(kind,filename)=>{if(/\.(js|mjs|jsx|ts|mts|tsx|vue|svelte)$/i.test(filename)){const link=document.head.querySelector("link[rel=stylesheet][href^='%s']");if(link)link.href="%s&t="+Date.now().toString(36)}});`, unocss, unocss)
298302
u := &url.URL{Path: pathname}
299303
u = u.ResolveReference(&url.URL{Path: "uno.css"})
300304
filename := filepath.Join(d.rootDir, u.Path)

0 commit comments

Comments
 (0)