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