Skip to content

Commit

Permalink
feat: implement unocss hmr
Browse files Browse the repository at this point in the history
  • Loading branch information
enpitsuLin committed Aug 4, 2023
1 parent ff26825 commit 9c09210
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 19 deletions.
25 changes: 25 additions & 0 deletions packages/userscript/plugins/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

const sheetsMap = new Map<string, HTMLStyleElement>()

export function updateStyle(id: string, content: string): HTMLStyleElement {
let style = sheetsMap.get(id)
if (!style) {
style = document.createElement('style')
style.setAttribute('type', 'text/css')
style.setAttribute('data-vite-dev-id', id)
style.textContent = content

} else {
style.textContent = content
}
sheetsMap.set(id, style)
return style
}

export function removeStyle(id: string): void {
const style = sheetsMap.get(id)
if (style) {
style.remove()
sheetsMap.delete(id)
}
}
60 changes: 60 additions & 0 deletions packages/userscript/plugins/unocss.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { type Plugin } from 'vite'
import Unocss from 'unocss/vite'

export function UnocssClientPlugin(): Plugin[] {
const plugins = Unocss()

const globalPlugin = plugins.find(i => i.name === 'unocss:global')
const globalPostPlugin = plugins.find(i => i.name === 'unocss:global:post')
const rest = plugins.filter(i => !['unocss:global', 'unocss:global:post'].includes(i.name))

return [
...rest,
{
name: "redirect:client",
enforce: "pre",
async resolveId(source, importer, options) {

if (source === '/@ud/client') {
return 'plugins/client.ts'
}
},
},
globalPlugin,
{
...globalPostPlugin,
async transform(_code, id, options) {
const data = await (globalPostPlugin.transform as any)(_code, id, options)

if (data && id === '/__uno.css') {
const { code: outcode } = data
const l3 = outcode.split('\n')[2] as string
const css = l3.substring('const __vite__css = "'.length, l3.length - 1)
const code = [
`import {updateStyle,removeStyle} from '/@ud/client'`,
`const __vite__id = ${JSON.stringify(id)}`,
`const __vite__css = "${css}"`,
`import.meta.hot.accept()`,
`export default updateStyle(__vite__id,__vite__css)`,
`import.meta.hot.prune(() => removeStyle(__vite__id))
if (import.meta.hot) {
try {
let hash = __vite__css.match(/__uno_hash_(\\w{6})/)
hash = hash && hash[1]
if (!hash)
console.warn('[unocss-hmr]', 'failed to get unocss hash, hmr might not work')
else
await import.meta.hot.send('unocss:hmr', ['__ALL__', hash]);
} catch (e) {
console.warn('[unocss-hmr]', e)
}
if (!import.meta.url.includes('?'))
await new Promise(resolve => setTimeout(resolve, 100))}`
].join('\n')

return { code }
}
},
},
]
}
20 changes: 2 additions & 18 deletions packages/userscript/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import reset from '@unocss/reset/tailwind-compat.css?raw'
import zh from '@userjs-digger/locales/zh.json'
import en from '@userjs-digger/locales/en.json'
import App from './App.vue'
import { attachUnocss } from './utils/unocss'

const settings = useUserjsDiggerSettings()

Expand Down Expand Up @@ -34,29 +35,12 @@ function initUserjsDigger(attachShadow = HTMLElement.prototype.attachShadow) {
constructor() {
super()
const app = document.createElement('div')


const shadow = attachShadow.call(this, { mode: 'open' })

const resetStyle = document.createElement('style')
resetStyle.innerHTML = reset


if (import.meta.env.DEV) {
const style = document.createElement('link')
style.rel = "stylesheet"
const url = new URL(import.meta.url)
style.href = new URL(`./__uno.css`, `${url.protocol}${url.host}`).href

shadow.appendChild(style)
}
else {
import('uno.css?raw').then(({ default: css }) => {
const style = document.createElement('style')
style.innerText = css as string
shadow.appendChild(style)
})
}
attachUnocss(shadow)
shadow.appendChild(resetStyle)
shadow.appendChild(app)

Expand Down
18 changes: 18 additions & 0 deletions packages/userscript/src/utils/unocss.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import unocss from 'uno.css?inline'

export function attachUnocss(root: ShadowRoot) {
if (import.meta.env.DEV) {
root.appendChild(unocss as any)
}
else {
import('uno.css?raw').then(({ default: css }) => {
const style = document.createElement('style')
style.innerText = css as string
root.appendChild(style)
})
}
}

if (import.meta.hot) {
import.meta.hot.accept(console.log)
}
3 changes: 2 additions & 1 deletion packages/userscript/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import monkey, { cdn, util } from 'vite-plugin-monkey'
import Unocss from 'unocss/vite'
import { UnocssBuildPlugin } from './plugins/build'
import pkg from './package.json'
import { UnocssClientPlugin } from './plugins/unocss'

// https://vitejs.dev/config/
export default defineConfig(async ({ command }) => {
const UnocssPlugin: Plugin[]
= command === 'serve' ? Unocss() : UnocssBuildPlugin()
= command === 'serve' ? UnocssClientPlugin() : UnocssBuildPlugin()
return {
build: {
lib: {
Expand Down

0 comments on commit 9c09210

Please sign in to comment.