Skip to content

Commit 082f306

Browse files
committed
pef: literalNodes
1 parent 3ab4800 commit 082f306

File tree

1 file changed

+19
-24
lines changed

1 file changed

+19
-24
lines changed

docs/.vitepress/plugins/mirror.ts

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { simple } from 'acorn-walk';
2-
import type { ImportExpression } from 'acorn';
2+
import type { ImportExpression, Literal } from 'acorn';
33
import MagicString from 'magic-string';
44
import fs from 'node:fs/promises';
55
import process from 'node:process';
@@ -15,8 +15,6 @@ const useMirror = process.env.MIRROR == `ON`;
1515

1616
const mirrorBaseUrl = `https://registry.npmmirror.com/@gkd-kit/docs/${selfPkg.version}/files/.vitepress/dist`;
1717

18-
const includesDynamicImport = /import\s*\(/;
19-
2018
export const mirror = (): Plugin | undefined => {
2119
if (!useMirror) return;
2220
return {
@@ -38,34 +36,31 @@ export const mirror = (): Plugin | undefined => {
3836
if (
3937
chunk.type == 'chunk' &&
4038
chunk.fileName.endsWith(`.js`) &&
41-
chunk.code.match(includesDynamicImport)
39+
chunk.code.includes('/assets/')
4240
) {
4341
const ast = this.parse(chunk.code);
44-
const nodes: ImportExpression[] = [];
42+
const literalNodes: Literal[] = [];
4543
simple(ast, {
46-
ImportExpression(node) {
47-
nodes.push(node);
44+
Literal(node) {
45+
if (
46+
typeof node.value === 'string' &&
47+
node.value.startsWith('/assets/')
48+
) {
49+
literalNodes.push(node);
50+
}
4851
},
4952
});
50-
if (nodes.length == 0) {
51-
return;
52-
}
53-
const ms = new MagicString(chunk.code);
54-
nodes
55-
.map((v) => v.source)
56-
.forEach((node) => {
57-
const start = node.start;
58-
const end = node.end;
59-
const code = chunk.code.slice(start, end);
60-
ms.overwrite(
61-
start,
62-
end,
63-
`((u)=>{if(u.startsWith('/')){return${JSON.stringify(
64-
mirrorBaseUrl,
65-
)}+u}return u})(${code})`,
53+
if (literalNodes.length) {
54+
const ms = new MagicString(chunk.code);
55+
literalNodes.forEach((n) => {
56+
ms.update(
57+
n.start,
58+
n.end,
59+
JSON.stringify(mirrorBaseUrl + String(n.value)),
6660
);
6761
});
68-
chunk.code = ms.toString();
62+
chunk.code = ms.toString();
63+
}
6964
}
7065
});
7166
},

0 commit comments

Comments
 (0)