-
Notifications
You must be signed in to change notification settings - Fork 169
/
init.ts
46 lines (45 loc) · 1.81 KB
/
init.ts
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
import { dirname } from 'https://deno.land/std@0.93.0/path/mod.ts'
import { getAlephPkgUri, getRelativePath, toLocalUrl } from '../../server/helper.ts'
import util from '../../shared/util.ts'
import type { ServerApplication } from '../../types.ts'
export async function init(app: ServerApplication) {
if (app.mode === 'development') {
const alephPkgUri = getAlephPkgUri()
app.injectCode('hmr', (url: string, code: string) => {
if (code.includes('$RefreshReg$(')) {
const refreshModuleUrl = getRelativePath(
dirname(toLocalUrl(url)),
toLocalUrl(`${alephPkgUri}/framework/react/refresh.js`)
)
return [
`import { RefreshRuntime, performReactRefresh } from ${JSON.stringify(refreshModuleUrl)};`,
'',
'const prevRefreshReg = window.$RefreshReg$;',
'const prevRefreshSig = window.$RefreshSig$;',
`window.$RefreshReg$ = (type, id) => RefreshRuntime.register(type, ${JSON.stringify(url)} + "#" + id);`,
'window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;',
'',
util.trimSuffix(code.trim(), 'import.meta.hot.accept();'),
'window.$RefreshReg$ = prevRefreshReg;',
'window.$RefreshSig$ = prevRefreshSig;',
'import.meta.hot.accept(performReactRefresh);'
].join('\n')
}
return code
})
app.injectCode('compilation', (url: string, code: string) => {
if (url === '/main.js') {
return [
`import ".${toLocalUrl(`${alephPkgUri}/framework/react/refresh.js`)}";`,
code
].join('\n')
}
return code
})
await app.addModule(`${alephPkgUri}/framework/react/refresh.ts`)
Object.assign(globalThis, {
$RefreshReg$: () => { },
$RefreshSig$: () => (type: any) => type,
})
}
}