/
hmr.js
70 lines (57 loc) · 1.85 KB
/
hmr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { foo as depFoo, nestedFoo } from './hmrDep'
export const foo = 1
text('.app', foo)
text('.dep', depFoo)
text('.nested', nestedFoo)
if (import.meta.hot) {
import.meta.hot.accept(({ foo }) => {
console.log('(self-accepting 1) foo is now:', foo)
})
import.meta.hot.accept(({ foo }) => {
console.log('(self-accepting 2) foo is now:', foo)
})
const handleDep = (type, newFoo, newNestedFoo) => {
console.log(`(${type}) foo is now: ${newFoo}`)
console.log(`(${type}) nested foo is now: ${newNestedFoo}`)
text('.dep', newFoo)
text('.nested', newNestedFoo)
}
import.meta.hot.accept('./hmrDep', ({ foo, nestedFoo }) => {
handleDep('single dep', foo, nestedFoo)
})
import.meta.hot.accept(['./hmrDep'], ([{ foo, nestedFoo }]) => {
handleDep('multi deps', foo, nestedFoo)
})
import.meta.hot.dispose(() => {
console.log(`foo was:`, foo)
})
import.meta.hot.on('vite:beforeUpdate', (event) => {
console.log(`>>> vite:beforeUpdate -- ${event.type}`)
const cssUpdate = event.updates.find(
(update) =>
update.type === 'css-update' && update.path.match('global.css')
)
if (cssUpdate) {
const el = document.querySelector('#global-css')
text('.css-prev', el.href)
// We don't have a vite:afterUpdate event, but updates are currently sync
setTimeout(() => {
text('.css-post', el.href)
}, 0)
}
})
import.meta.hot.on('vite:error', (event) => {
console.log(`>>> vite:error -- ${event.type}`)
})
import.meta.hot.on('foo', ({ msg }) => {
text('.custom', msg)
})
// send custom event to server to calculate 1 + 2
import.meta.hot.send('remote-add', { a: 1, b: 2 })
import.meta.hot.on('remote-add-result', ({ result }) => {
text('.custom-communication', result)
})
}
function text(el, text) {
document.querySelector(el).textContent = text
}