forked from Kholid060/inspect-css
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-hmr.ts
More file actions
50 lines (41 loc) · 1.3 KB
/
add-hmr.ts
File metadata and controls
50 lines (41 loc) · 1.3 KB
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
import * as path from 'path';
import { readFileSync } from 'fs';
import type { PluginOption } from 'vite';
const isDev = process.env.__DEV__ === 'true';
const DUMMY_CODE = `export default function(){};`;
function getInjectionCode(fileName: string): string {
return readFileSync(
path.resolve(__dirname, '..', 'reload', 'injections', fileName),
{ encoding: 'utf8' },
);
}
type Config = {
background?: boolean;
view?: boolean;
};
export default function addHmr(config?: Config): PluginOption {
const { background = false, view = true } = config || {};
const idInBackgroundScript = 'virtual:reload-on-update-in-background-script';
const idInView = 'virtual:reload-on-update-in-view';
const scriptHmrCode = isDev ? getInjectionCode('script.js') : DUMMY_CODE;
const viewHmrCode = isDev ? getInjectionCode('view.js') : DUMMY_CODE;
return {
name: 'add-hmr',
resolveId(id) {
if (id === idInBackgroundScript || id === idInView) {
return getResolvedId(id);
}
},
load(id) {
if (id === getResolvedId(idInBackgroundScript)) {
return background ? scriptHmrCode : DUMMY_CODE;
}
if (id === getResolvedId(idInView)) {
return view ? viewHmrCode : DUMMY_CODE;
}
},
};
}
function getResolvedId(id: string) {
return '\0' + id;
}