Skip to content

Commit

Permalink
wip: tweaks for vitepress
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Dec 28, 2020
1 parent 2d93dff commit 49dac87
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 32 deletions.
34 changes: 3 additions & 31 deletions packages/plugin-vue/src/handleHotUpdate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import fs from 'fs'
import _debug from 'debug'
import { SFCBlock, SFCDescriptor } from '@vue/compiler-sfc'
import {
Expand All @@ -17,25 +16,18 @@ const debug = _debug('vite:hmr')
export async function handleHotUpdate(
file: string,
modules: ModuleNode[],
read: () => string | Promise<string>,
server: ViteDevServer
): Promise<ModuleNode[] | void> {
if (!file.endsWith('.vue')) {
return
}

const prevDescriptor = getDescriptor(file)
if (!prevDescriptor) {
// file hasn't been requested yet (e.g. async component)
return
}

let content = fs.readFileSync(file, 'utf-8')
if (!content) {
await untilModified(file)
content = fs.readFileSync(file, 'utf-8')
}

setPrevDescriptor(file, prevDescriptor)

const content = await read()
const { descriptor } = createDescriptor(
file,
content,
Expand Down Expand Up @@ -147,26 +139,6 @@ export async function handleHotUpdate(
return [...affectedModules].filter(Boolean) as ModuleNode[]
}

// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
// change event and sometimes this can be too early and get an empty buffer.
// Poll until the file's modified time has changed before reading again.
async function untilModified(file: string) {
const mtime = fs.statSync(file).mtimeMs
return new Promise((r) => {
let n = 0
const poll = async () => {
n++
const newMtime = fs.statSync(file).mtimeMs
if (newMtime !== mtime || n > 10) {
r(0)
} else {
setTimeout(poll, 10)
}
}
setTimeout(poll, 10)
})
}

function isEqualBlock(a: SFCBlock | null, b: SFCBlock | null) {
if (!a && !b) return true
if (!a || !b) return false
Expand Down
7 changes: 6 additions & 1 deletion packages/plugin-vue/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin {
return {
name: 'vite:vue',

handleHotUpdate,
handleHotUpdate(file, mods, read, server) {
if (!filter(file)) {
return
}
return handleHotUpdate(file, mods, read, server)
},

config(config) {
// provide default values for vue runtime esm defines
Expand Down

0 comments on commit 49dac87

Please sign in to comment.