-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
replace-browser-modules.ts
44 lines (40 loc) · 1.11 KB
/
replace-browser-modules.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
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { Plugin } from 'vite';
const resolve = (path: string) => fileURLToPath(new URL(`../${path}`, import.meta.url));
const REPLACED_MODULES = [
'crypto',
'fs',
'hookActions',
'path',
'performance',
'process',
'resolveId'
];
const resolutions: ReadonlyMap<string, string> = new Map(
REPLACED_MODULES.flatMap(module => {
const originalId = resolve(`src/utils/${module}`);
const replacementId = resolve(`browser/src/${module}.ts`);
return [
[originalId, replacementId],
[`${originalId}.ts`, replacementId]
];
})
);
export default function replaceBrowserModules(): Plugin {
return {
apply: 'serve',
enforce: 'pre',
name: 'replace-browser-modules',
resolveId(source, importer) {
if (importer && source[0] === '.') {
return resolutions.get(join(dirname(importer), source));
}
},
transformIndexHtml(html) {
// Unfortunately, picomatch sneaks as a dedendency into the dev bundle.
// This fixes an error.
return html.replace('</head>', '<script>window.process={}</script></head>');
}
};
}