-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
index.ts
69 lines (62 loc) · 2.04 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { parse } from 'acorn';
import { walk } from 'estree-walker';
import MagicString from 'magic-string';
import type { Plugin } from 'vite';
import type { AstroSettings } from '../@types/astro';
import { isMarkdownFile } from '../core/util.js';
// Check for `Astro.glob()`. Be very forgiving of whitespace. False positives are okay.
const ASTRO_GLOB_REGEX = /Astro2?\s*\.\s*glob\s*\(/;
interface AstroPluginOptions {
settings: AstroSettings;
}
export default function astro(_opts: AstroPluginOptions): Plugin {
return {
name: 'astro:postprocess',
async transform(code, id) {
// Currently only supported in ".astro" and ".md" (or any alternative markdown file extension like `.markdown`) files
if (!id.endsWith('.astro') && !isMarkdownFile(id)) {
return null;
}
// Optimization: Detect usage with a quick string match.
// Only perform the transform if this function is found
if (!ASTRO_GLOB_REGEX.test(code)) {
return null;
}
let s: MagicString | undefined;
const ast = parse(code, {
ecmaVersion: 'latest',
sourceType: 'module',
});
walk(ast, {
enter(node: any) {
// Transform `Astro.glob("./pages/*.astro")` to `Astro.glob(import.meta.glob("./pages/*.astro"), () => "./pages/*.astro")`
// Also handle for `Astro2.glob()`
if (
node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
node.callee.property.name === 'glob' &&
(node.callee.object.name === 'Astro' || node.callee.object.name === 'Astro2') &&
node.arguments.length
) {
const firstArgStart = node.arguments[0].start;
const firstArgEnd = node.arguments[0].end;
const lastArgEnd = node.arguments[node.arguments.length - 1].end;
const firstArg = code.slice(firstArgStart, firstArgEnd);
s ??= new MagicString(code);
s.overwrite(
firstArgStart,
lastArgEnd,
`import.meta.glob(${firstArg}), () => ${firstArg}`
);
}
},
});
if (s) {
return {
code: s.toString(),
map: s.generateMap(),
};
}
},
};
}