Skip to content

Commit

Permalink
feat(vite): introduce hmrTopLevelAwait option (#2066)
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
4 people committed Jan 12, 2023
1 parent 61d913f commit 7a4b2ed
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 12 deletions.
29 changes: 20 additions & 9 deletions packages/vite/src/modes/global/dev.ts
@@ -1,13 +1,14 @@
import type { Plugin, Update, ViteDevServer, ResolvedConfig as ViteResolvedConfig } from 'vite'
import type { GenerateResult, UnocssPluginContext } from '@unocss/core'
import { notNull } from '@unocss/core'
import type { VitePluginConfig } from 'unocss/vite'
import { LAYER_MARK_ALL, getHash, getPath, resolveId, resolveLayer } from '../../integration'

const WARN_TIMEOUT = 20000
const WS_EVENT_PREFIX = 'unocss:hmr'
const HASH_LENGTH = 6

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

// inject css modules to send callback on css load
if (layer && code.includes('import.meta.hot')) {
return `${code}
if (import.meta.hot) {
try { await import.meta.hot.send('${WS_EVENT_PREFIX}', ['${layer}', __vite__css.slice(2,${2 + HASH_LENGTH})]); }
catch (e) { console.warn('[unocss-hmr]', e) }
if (!import.meta.url.includes('?'))
await new Promise(resolve => setTimeout(resolve, 100))
}`
let hmr = `
try {
await import.meta.hot.send('${WS_EVENT_PREFIX}', ['${layer}', __vite__css.slice(2,${2 + HASH_LENGTH})]);
} catch (e) {
console.warn('[unocss-hmr]', e)
}
if (!import.meta.url.includes('?'))
await new Promise(resolve => setTimeout(resolve, 100))`

const config = await getConfig() as VitePluginConfig

if (config.hmrTopLevelAwait === false)
hmr = `;(async function() {${hmr}\n})()`

hmr = `\nif (import.meta.hot) {${hmr}}`

return code + hmr
}
},
},
Expand Down
16 changes: 15 additions & 1 deletion packages/vite/src/types.ts
Expand Up @@ -21,17 +21,31 @@ export interface VitePluginConfig<Theme extends {} = {}> extends UserConfig<Them
* @default 'global'
*/
mode?: 'global' | 'per-module' | 'vue-scoped' | 'svelte-scoped' | 'dist-chunk' | 'shadow-dom'

/**
* Transform CSS for `@apply` directive
*
* @experimental
* @default false
*/
transformCSS?: boolean | 'pre' | 'post'

/**
* Make the generated css processed by postcss (https://vitejs.dev/guide/features.html#postcss)
*
* make the generated css processed by postcss (https://vitejs.dev/guide/features.html#postcss)
* @default true
*/
postcss?: boolean

/**
* Use top level await in HMR code to avoid FOUC on dev time.
*
* You usually don't need to disable this, unless you are developing on
* a browser that does not support top level await.
*
* This will only affect on dev time.
*
* @default true
*/
hmrTopLevelAwait?: boolean
}
1 change: 1 addition & 0 deletions playground/src/auto-imports.d.ts
Expand Up @@ -111,6 +111,7 @@ declare global {
const useArrayMap: typeof import('@vueuse/core')['useArrayMap']
const useArrayReduce: typeof import('@vueuse/core')['useArrayReduce']
const useArraySome: typeof import('@vueuse/core')['useArraySome']
const useArrayUnique: typeof import('@vueuse/core')['useArrayUnique']
const useAsyncQueue: typeof import('@vueuse/core')['useAsyncQueue']
const useAsyncState: typeof import('@vueuse/core')['useAsyncState']
const useAttrs: typeof import('vue')['useAttrs']
Expand Down
6 changes: 4 additions & 2 deletions playground/vite.config.ts
Expand Up @@ -3,7 +3,7 @@ import Vue from '@vitejs/plugin-vue'
import Inspect from 'vite-plugin-inspect'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Unocss from '@unocss/vite'
import UnoCSS from '@unocss/vite'
import { alias } from '../alias'

export default defineConfig({
Expand All @@ -13,7 +13,9 @@ export default defineConfig({
},
plugins: [
Vue(),
Unocss(),
UnoCSS({
// hmrTopLevelAwait: false,
}),
Inspect(),
Components({
dirs: [
Expand Down

0 comments on commit 7a4b2ed

Please sign in to comment.