Skip to content

Commit 7a4b2ed

Browse files
LittleSoundsudongyuerzyyvantfu
authored
feat(vite): introduce hmrTopLevelAwait option (#2066)
Co-authored-by: Frozen FIsh <76603360+sudongyuer@users.noreply.github.com> Co-authored-by: Chris <1633711653@qq.com> Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
1 parent 61d913f commit 7a4b2ed

File tree

4 files changed

+40
-12
lines changed

4 files changed

+40
-12
lines changed

packages/vite/src/modes/global/dev.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import type { Plugin, Update, ViteDevServer, ResolvedConfig as ViteResolvedConfig } from 'vite'
22
import type { GenerateResult, UnocssPluginContext } from '@unocss/core'
33
import { notNull } from '@unocss/core'
4+
import type { VitePluginConfig } from 'unocss/vite'
45
import { LAYER_MARK_ALL, getHash, getPath, resolveId, resolveLayer } from '../../integration'
56

67
const WARN_TIMEOUT = 20000
78
const WS_EVENT_PREFIX = 'unocss:hmr'
89
const HASH_LENGTH = 6
910

10-
export function GlobalModeDevPlugin({ uno, tokens, tasks, flushTasks, affectedModules, onInvalidate, extract, filter }: UnocssPluginContext): Plugin[] {
11+
export function GlobalModeDevPlugin({ uno, tokens, tasks, flushTasks, affectedModules, onInvalidate, extract, filter, getConfig }: UnocssPluginContext): Plugin[] {
1112
const servers: ViteDevServer[] = []
1213
let base = ''
1314
const entries = new Set<string>()
@@ -162,18 +163,28 @@ export function GlobalModeDevPlugin({ uno, tokens, tasks, flushTasks, affectedMo
162163
return env.command === 'serve' && !config.build?.ssr
163164
},
164165
enforce: 'post',
165-
transform(code, id) {
166+
async transform(code, id) {
166167
const layer = resolveLayer(getPath(id))
167168

168169
// inject css modules to send callback on css load
169170
if (layer && code.includes('import.meta.hot')) {
170-
return `${code}
171-
if (import.meta.hot) {
172-
try { await import.meta.hot.send('${WS_EVENT_PREFIX}', ['${layer}', __vite__css.slice(2,${2 + HASH_LENGTH})]); }
173-
catch (e) { console.warn('[unocss-hmr]', e) }
174-
if (!import.meta.url.includes('?'))
175-
await new Promise(resolve => setTimeout(resolve, 100))
176-
}`
171+
let hmr = `
172+
try {
173+
await import.meta.hot.send('${WS_EVENT_PREFIX}', ['${layer}', __vite__css.slice(2,${2 + HASH_LENGTH})]);
174+
} catch (e) {
175+
console.warn('[unocss-hmr]', e)
176+
}
177+
if (!import.meta.url.includes('?'))
178+
await new Promise(resolve => setTimeout(resolve, 100))`
179+
180+
const config = await getConfig() as VitePluginConfig
181+
182+
if (config.hmrTopLevelAwait === false)
183+
hmr = `;(async function() {${hmr}\n})()`
184+
185+
hmr = `\nif (import.meta.hot) {${hmr}}`
186+
187+
return code + hmr
177188
}
178189
},
179190
},

packages/vite/src/types.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,31 @@ export interface VitePluginConfig<Theme extends {} = {}> extends UserConfig<Them
2121
* @default 'global'
2222
*/
2323
mode?: 'global' | 'per-module' | 'vue-scoped' | 'svelte-scoped' | 'dist-chunk' | 'shadow-dom'
24+
2425
/**
2526
* Transform CSS for `@apply` directive
2627
*
2728
* @experimental
2829
* @default false
2930
*/
3031
transformCSS?: boolean | 'pre' | 'post'
32+
3133
/**
34+
* Make the generated css processed by postcss (https://vitejs.dev/guide/features.html#postcss)
3235
*
33-
* make the generated css processed by postcss (https://vitejs.dev/guide/features.html#postcss)
3436
* @default true
3537
*/
3638
postcss?: boolean
39+
40+
/**
41+
* Use top level await in HMR code to avoid FOUC on dev time.
42+
*
43+
* You usually don't need to disable this, unless you are developing on
44+
* a browser that does not support top level await.
45+
*
46+
* This will only affect on dev time.
47+
*
48+
* @default true
49+
*/
50+
hmrTopLevelAwait?: boolean
3751
}

playground/src/auto-imports.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ declare global {
111111
const useArrayMap: typeof import('@vueuse/core')['useArrayMap']
112112
const useArrayReduce: typeof import('@vueuse/core')['useArrayReduce']
113113
const useArraySome: typeof import('@vueuse/core')['useArraySome']
114+
const useArrayUnique: typeof import('@vueuse/core')['useArrayUnique']
114115
const useAsyncQueue: typeof import('@vueuse/core')['useAsyncQueue']
115116
const useAsyncState: typeof import('@vueuse/core')['useAsyncState']
116117
const useAttrs: typeof import('vue')['useAttrs']

playground/vite.config.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import Vue from '@vitejs/plugin-vue'
33
import Inspect from 'vite-plugin-inspect'
44
import Components from 'unplugin-vue-components/vite'
55
import AutoImport from 'unplugin-auto-import/vite'
6-
import Unocss from '@unocss/vite'
6+
import UnoCSS from '@unocss/vite'
77
import { alias } from '../alias'
88

99
export default defineConfig({
@@ -13,7 +13,9 @@ export default defineConfig({
1313
},
1414
plugins: [
1515
Vue(),
16-
Unocss(),
16+
UnoCSS({
17+
// hmrTopLevelAwait: false,
18+
}),
1719
Inspect(),
1820
Components({
1921
dirs: [

0 commit comments

Comments
 (0)