-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathfis3plugin.ts
62 lines (49 loc) · 1.61 KB
/
fis3plugin.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
50
51
52
53
54
55
56
57
58
59
60
61
62
import MagicString from 'magic-string';
import {createFilter} from 'rollup-pluginutils';
import type {Plugin} from 'vite';
export default function fis3replace(
options: {
include?: any;
exclude?: any;
sourcemap?: boolean;
sourceMap?: boolean;
} = {}
): Plugin {
const filter = createFilter(options.include, options.exclude);
return {
name: 'fis3',
enforce: 'pre',
apply: 'serve',
transform(code: string, id: string) {
if (!filter(id)) return null;
const magicString = new MagicString(code);
let hasReplacements = false;
let start;
let end;
code = code.replace(
/(__uri|__inline)\(\s*('|")(.*?)\2\s*\)/g,
(_, directive, quote, target, index) => {
hasReplacements = true;
start = index;
end = start + _.length;
if (directive === '__uri') {
let replacement = `new URL(${quote}${target}${quote}, import.meta.url).href`;
magicString.overwrite(start, end, replacement);
} else if (directive === '__inline') {
let varname = target
.replace(/[^a-zA-Z0-9]/g, '')
.replace(/^\d+/, '');
magicString.prepend(`import ${varname} from '${target}?inline';\n`);
magicString.overwrite(start, end, `${varname}`);
}
return _;
}
);
if (!hasReplacements) return null;
const result: any = {code: magicString.toString()};
if (options.sourceMap !== false && options.sourcemap !== false)
result.map = magicString.generateMap({hires: true});
return result;
}
};
}