-
-
Notifications
You must be signed in to change notification settings - Fork 600
/
Copy pathindex.ts
43 lines (31 loc) · 1.02 KB
/
index.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
import * as path from 'path';
import type { Plugin } from 'rollup';
import type { RollupVirtualOptions } from '../types';
const PREFIX = `\0virtual:`;
export default function virtual(modules: RollupVirtualOptions): Plugin {
const resolvedIds = new Map<string, string>();
Object.keys(modules).forEach((id) => {
resolvedIds.set(path.resolve(id), modules[id]);
});
return {
name: 'virtual',
resolveId(id, importer) {
if (id in modules) return PREFIX + id;
if (importer) {
const importerNoPrefix = importer.startsWith(PREFIX)
? importer.slice(PREFIX.length)
: importer;
const resolved = path.resolve(path.dirname(importerNoPrefix), id);
if (resolvedIds.has(resolved)) return PREFIX + resolved;
}
return null;
},
load(id) {
if (id.startsWith(PREFIX)) {
const idNoPrefix = id.slice(PREFIX.length);
return idNoPrefix in modules ? modules[idNoPrefix] : resolvedIds.get(idNoPrefix);
}
return null;
}
};
}