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

fix: hmr on web worker #6483

Closed
Closed
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
18 changes: 18 additions & 0 deletions packages/playground/worker/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,22 @@
)
})
w2.port.start()

if (import.meta.hot) {
import.meta.hot.accept(
[
'./my-worker?worker',
'./my-worker?inline',
'./possible-ts-output-worker?worker',
'./workerImport'
],
([a, b, c, d]) => {
// the callback receives the updated modules in an Array
console.log(a)
console.log(b)
console.log(c)
console.log(d)
}
)
}
</script>
11 changes: 10 additions & 1 deletion packages/playground/worker/my-worker.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import { msg, mode } from './workerImport'
import { msg as originalMsg, mode } from './workerImport'
import { bundleWithPlugin } from './test-plugin'

let msg = originalMsg

self.onmessage = (e) => {
if (e.data === 'ping') {
self.postMessage({ msg, mode, bundleWithPlugin })
}
}

if (import.meta.hot) {
import.meta.hot.accept('./workerImport', (newImportModule) => {
if (newImportModule && newImportModule.msg) msg = newImportModule.msg
else console.log(`Unexpected HMR received: ${newImportModule}`)
})
}
11 changes: 10 additions & 1 deletion packages/playground/worker/possible-ts-output-worker.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { msg, mode } from './workerImport'
import { msg as originalMsg, mode } from './workerImport'

let msg = originalMsg

self.onmessage = (e) => {
if (e.data === 'ping') {
self.postMessage({ msg, mode })
}
}

if (import.meta.hot) {
import.meta.hot.accept('./workerImport', (newImportModule) => {
if (newImportModule && newImportModule.msg) msg = newImportModule.msg
else console.log(`Unexpected HMR received: ${newImportModule}`)
})
}
21 changes: 21 additions & 0 deletions packages/playground/worker/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"lib": ["ESNext", "DOM", "WebWorker"],
"moduleResolution": "Node",
"strict": true,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,

"useDefineForClassFields": true,
"importsNotUsedAsValues": "preserve"
},
"include": ["."]
}
2 changes: 1 addition & 1 deletion packages/playground/worker/workerImport.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export const msg = 'pong'
export const msg = 'pong2'
export const mode = process.env.NODE_ENV
64 changes: 50 additions & 14 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ socket.addEventListener('message', async ({ data }) => {
handleMessage(JSON.parse(data))
})

const onUi = typeof window !== 'undefined'
const logReloadMessage =
'[vite] running on worker, please reload the page manually!'

let isFirstUpdate = true

async function handleMessage(payload: HMRPayload) {
Expand Down Expand Up @@ -75,17 +79,19 @@ async function handleMessage(payload: HMRPayload) {
// this is only sent when a css file referenced with <link> is updated
let { path, timestamp } = update
path = path.replace(/\?.*/, '')
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = Array.from(
document.querySelectorAll<HTMLLinkElement>('link')
).find((e) => e.href.includes(path))
if (el) {
const newPath = `${base}${path.slice(1)}${
path.includes('?') ? '&' : '?'
}t=${timestamp}`
el.href = new URL(newPath, el.href).href
if (onUi) {
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = Array.from(
document.querySelectorAll<HTMLLinkElement>('link')
).find((e) => e.href.includes(path))
if (el) {
const newPath = `${base}${path.slice(1)}${
path.includes('?') ? '&' : '?'
}t=${timestamp}`
el.href = new URL(newPath, el.href).href
}
}
console.log(`[vite] css hot updated: ${path}`)
}
Expand All @@ -106,10 +112,20 @@ async function handleMessage(payload: HMRPayload) {
pagePath === payloadPath ||
(pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)
) {
if (!onUi) {
console.warn(logReloadMessage)
return
}

location.reload()
}
return
} else {
if (!onUi) {
console.warn(logReloadMessage)
return
}

location.reload()
}
break
Expand Down Expand Up @@ -171,16 +187,30 @@ const enableOverlay = __HMR_ENABLE_OVERLAY__
function createErrorOverlay(err: ErrorPayload['err']) {
if (!enableOverlay) return
clearErrorOverlay()
if (!onUi) {
console.log(`[vite] Internal Server Error\n${err.message}\n${err.stack}`)
return
}

document.body.appendChild(new ErrorOverlay(err))
}

function clearErrorOverlay() {
document
.querySelectorAll(overlayId)
.forEach((n) => (n as ErrorOverlay).close())
if (!onUi) {
// TODO: clear console?
// console.clear()
return
}

document.querySelectorAll(overlayId).forEach((n) =>
// @ts-ignore
(n as ErrorOverlay).close()
)
}

function hasErrorOverlay() {
if (!onUi) return false

return document.querySelectorAll(overlayId).length
}

Expand Down Expand Up @@ -221,6 +251,10 @@ socket.addEventListener('close', async ({ wasClean }) => {
if (wasClean) return
console.log(`[vite] server connection lost. polling for restart...`)
await waitForSuccessfulPing()
if (!onUi) {
console.warn(logReloadMessage)
return
}
location.reload()
})

Expand Down Expand Up @@ -448,6 +482,8 @@ export const createHotContext = (ownerPath: string) => {
decline() {},

invalidate() {
if (!onUi) return

// TODO should tell the server to re-perform hmr propagation
// from this module as root
location.reload()
Expand Down
143 changes: 82 additions & 61 deletions packages/vite/src/client/overlay.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import type { ErrorPayload } from 'types/hmrPayload'

const template = /*html*/ `
let ErrorOverlay:
| InstanceType<
typeof HTMLElement & {
text(selector: string, text: string, linkFiles?: boolean): void
close(): void
}
>
| any = typeof window !== 'undefined' ? Object : undefined

if (typeof window !== 'undefined') {
const template = /*html*/ `
<style>
:host {
position: fixed;
Expand Down Expand Up @@ -112,78 +122,89 @@ code {
</div>
`

const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g
const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm

export class ErrorOverlay extends HTMLElement {
root: ShadowRoot

constructor(err: ErrorPayload['err']) {
super()
this.root = this.attachShadow({ mode: 'open' })
this.root.innerHTML = template

codeframeRE.lastIndex = 0
const hasFrame = err.frame && codeframeRE.test(err.frame)
const message = hasFrame
? err.message.replace(codeframeRE, '')
: err.message
if (err.plugin) {
this.text('.plugin', `[plugin:${err.plugin}] `)
}
this.text('.message-body', message.trim())
const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g
const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm

// @ts-ignore
class DOMErrorOverlay extends HTMLElement implements ErrorOverlay {
root: ShadowRoot

constructor(err: ErrorPayload['err']) {
super()
this.root = this.attachShadow({ mode: 'open' })
this.root.innerHTML = template

codeframeRE.lastIndex = 0
const hasFrame = err.frame && codeframeRE.test(err.frame)
const message = hasFrame
? err.message.replace(codeframeRE, '')
: err.message
if (err.plugin) {
this.text('.plugin', `[plugin:${err.plugin}] `)
}
this.text('.message-body', message.trim())

const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)
if (err.loc) {
this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true)
} else if (err.id) {
this.text('.file', file)
}
const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)
if (err.loc) {
this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true)
} else if (err.id) {
this.text('.file', file)
}

if (hasFrame) {
this.text('.frame', err.frame!.trim())
if (hasFrame) {
this.text('.frame', err.frame!.trim())
}
this.text('.stack', err.stack, true)

this.root.querySelector('.window')!.addEventListener('click', (e) => {
e.stopPropagation()
})
this.addEventListener('click', () => {
this.close()
})
}
this.text('.stack', err.stack, true)

this.root.querySelector('.window')!.addEventListener('click', (e) => {
e.stopPropagation()
})
this.addEventListener('click', () => {
this.close()
})
}

text(selector: string, text: string, linkFiles = false): void {
const el = this.root.querySelector(selector)!
if (!linkFiles) {
el.textContent = text
} else {
let curIndex = 0
let match: RegExpExecArray | null
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match
if (index != null) {
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch('/__open-in-editor?file=' + encodeURIComponent(file))
text(selector: string, text: string, linkFiles = false): void {
const el = this.root.querySelector(selector)!
if (!linkFiles) {
el.textContent = text
} else {
let curIndex = 0
let match: RegExpExecArray | null
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match
if (index != null) {
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch('/__open-in-editor?file=' + encodeURIComponent(file))
}
el.appendChild(link)
curIndex += frag.length + file.length
}
el.appendChild(link)
curIndex += frag.length + file.length
}
}
}
}

close(): void {
this.parentNode?.removeChild(this)
close(): void {
this.parentNode?.removeChild(this)
}
}

ErrorOverlay = DOMErrorOverlay
}

export { ErrorOverlay }

export const overlayId = 'vite-error-overlay'
if (customElements && !customElements.get(overlayId)) {

if (
typeof window !== 'undefined' &&
customElements &&
!customElements.get(overlayId)
) {
customElements.define(overlayId, ErrorOverlay)
}