-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathviteStripDeps.ts
More file actions
52 lines (44 loc) · 1.65 KB
/
Copy pathviteStripDeps.ts
File metadata and controls
52 lines (44 loc) · 1.65 KB
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
import type { Plugin } from "vite";
import { simple as acornWalk } from "acorn-walk"
type ViteStripDepsOpts = {
ignoreList: string[]
}
export const viteStripDeps = ({ ignoreList = [] }: ViteStripDepsOpts): Plugin => {
let isProd = false;
return {
name: 'vite-strip-deps',
configResolved(config) {
isProd = config.isProduction
},
transform(code, id, options) {
if (!isProd) return;
if (ignoreList.findIndex((v) => id.endsWith(v)) < 0) return;
const ast = this.parse(code)
const exportedNames: string[] = [];
acornWalk(ast, {
ExportNamedDeclaration(node) {
let ids: string[];
switch (node.declaration?.type) {
case 'ClassDeclaration':
case 'FunctionDeclaration':
ids = [node.declaration.id.name];
break;
case 'VariableDeclaration':
ids = node.declaration.declarations
.map((v) => v.id.type == 'Identifier' ? v.id.name : undefined)
.filter((v) => v) as string[];
break;
default:
ids = [];
break;
}
exportedNames.push(...ids)
}
})
const replacedCode = exportedNames.map((v) => `export const ${v} = {}`).join(';\n');
return {
code: replacedCode
}
},
};
}