Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(vite): introduce hmrTopLevelAwait option #2066

Merged
merged 8 commits into from
Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 20 additions & 9 deletions packages/vite/src/modes/global/dev.ts
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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