-
Notifications
You must be signed in to change notification settings - Fork 417
Expand file tree
/
Copy pathtree-shake.ts
More file actions
388 lines (369 loc) · 14.1 KB
/
tree-shake.ts
File metadata and controls
388 lines (369 loc) · 14.1 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// All credit for this work goes to the amazing Next.js team.
// https://github.com/vercel/next.js/blob/canary/packages/next/build/babel/plugins/next-ssg-transform.ts
// This is adapted to work with routeData functions. It can be run in two modes, one which preserves the routeData and the Component in the same file, and one which creates a
import type * as Babel from "@babel/core";
import type { NodePath, PluginObj, PluginPass } from "@babel/core";
import type { Binding } from "@babel/traverse";
import { basename } from "pathe";
import type { Plugin, ResolvedConfig, ViteDevServer } from "vite";
type State = Omit<PluginPass, "opts"> & {
opts: { pick: string[] };
refs: Set<any>;
done: boolean;
};
function treeShakeTransform({ types: t }: typeof Babel): PluginObj<State> {
function getIdentifier(path: any) {
const parentPath = path.parentPath;
if (parentPath.type === "VariableDeclarator") {
const pp = parentPath;
const name = pp.get("id");
return name.node.type === "Identifier" ? name : null;
}
if (parentPath.type === "AssignmentExpression") {
const pp = parentPath;
const name = pp.get("left");
return name.node.type === "Identifier" ? name : null;
}
if (path.node.type === "ArrowFunctionExpression") {
return null;
}
return path.node.id && path.node.id.type === "Identifier" ? path.get("id") : null;
}
function isIdentifierReferenced(ident: any) {
const b: Binding | undefined = ident.scope.getBinding(ident.node.name);
if (b?.referenced) {
if (b.path.type === "FunctionDeclaration") {
return !b.constantViolations
.concat(b.referencePaths)
.every(ref => ref.findParent(p => p === b.path));
}
return true;
}
return false;
}
function markFunction(path: any, state: any) {
const ident = getIdentifier(path);
if (ident && ident.node && isIdentifierReferenced(ident)) {
state.refs.add(ident);
}
}
function markImport(path: any, state: any) {
const local = path.get("local");
if (isIdentifierReferenced(local)) {
state.refs.add(local);
}
}
return {
visitor: {
Program: {
enter(path, state) {
state.refs = new Set();
state.done = false;
path.traverse(
{
VariableDeclarator(variablePath, variableState: any) {
if (variablePath.node.id.type === "Identifier") {
const local = variablePath.get("id");
if (isIdentifierReferenced(local)) {
variableState.refs.add(local);
}
} else if (variablePath.node.id.type === "ObjectPattern") {
const pattern = variablePath.get("id");
const properties = pattern.get("properties") as Array<NodePath>;
properties.forEach(p => {
const local = p.get(
p.node.type === "ObjectProperty"
? "value"
: p.node.type === "RestElement"
? "argument"
: (() => {
throw new Error("invariant");
})(),
);
if (isIdentifierReferenced(local)) {
variableState.refs.add(local);
}
});
} else if (variablePath.node.id.type === "ArrayPattern") {
const pattern = variablePath.get("id");
const elements = pattern.get("elements") as Array<NodePath>;
elements.forEach(e => {
let local: NodePath<any>;
if (e.node && e.node.type === "Identifier") {
local = e;
} else if (e.node && e.node.type === "RestElement") {
local = e.get("argument");
} else {
return;
}
if (isIdentifierReferenced(local)) {
variableState.refs.add(local);
}
});
}
},
ExportDefaultDeclaration(exportNamedPath) {
if (state.opts.pick && !state.opts.pick.includes("default")) {
const decl = exportNamedPath.get("declaration");
if (decl.node) {
// Keep the declaration, just remove the export
exportNamedPath.replaceWith(decl.node);
} else {
exportNamedPath.remove();
}
}
},
ExportNamedDeclaration(exportNamedPath) {
if (!state.opts.pick) {
return;
}
const specifiers = exportNamedPath.get("specifiers");
// Handle: export { foo, bar }
if (specifiers.length) {
specifiers.forEach(s => {
const exportedName = t.isIdentifier(s.node.exported)
? s.node.exported.name
: s.node.exported.value;
if (!state.opts.pick.includes(exportedName)) {
s.remove(); // Remove from export list, but keep the local binding
}
});
if (exportNamedPath.node.specifiers.length < 1) {
exportNamedPath.remove(); // Remove empty export statement
}
return;
}
const decl = exportNamedPath.get("declaration");
if (decl == null || decl.node == null) {
return;
}
switch (decl.node.type) {
case "FunctionDeclaration": {
const name = decl.node.id?.name;
if (name && !state.opts.pick.includes(name)) {
// REPLACE export function foo() {} with function foo() {}
// Don't remove - just remove the export!
exportNamedPath.replaceWith(decl.node);
}
break;
}
case "VariableDeclaration": {
const inner = decl.get("declarations");
inner.forEach(d => {
if (d.node.id.type !== "Identifier") return;
const name = d.node.id.name;
if (!state.opts.pick.includes(name)) {
// Keep the variable, just not exported
// Replace export const foo = ... with const foo = ...
exportNamedPath.replaceWith(decl.node!);
}
});
break;
}
case "ClassDeclaration": {
const name = decl.node.id?.name;
if (name && !state.opts.pick.includes(name)) {
exportNamedPath.replaceWith(decl.node);
}
break;
}
default: {
break;
}
}
},
FunctionDeclaration: markFunction,
FunctionExpression: markFunction,
ArrowFunctionExpression: markFunction,
ImportSpecifier: markImport,
ImportDefaultSpecifier: markImport,
ImportNamespaceSpecifier: markImport,
ImportDeclaration: (path, state) => {
if (
path.node.source.value.endsWith(".css") &&
state.opts.pick &&
!state.opts.pick.includes("$css")
) {
path.remove();
}
},
},
state,
);
const refs = state.refs;
let count = 0;
const sweepFunction = (sweepPath: any) => {
const ident = getIdentifier(sweepPath);
if (ident && ident.node && refs.has(ident) && !isIdentifierReferenced(ident)) {
++count;
if (
t.isAssignmentExpression(sweepPath.parentPath) ||
t.isVariableDeclarator(sweepPath.parentPath)
) {
sweepPath.parentPath.remove();
} else {
sweepPath.remove();
}
}
};
function sweepImport(sweepPath: any) {
const local = sweepPath.get("local");
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
sweepPath.remove();
if (sweepPath.parent.specifiers.length === 0) {
sweepPath.parentPath.remove();
}
}
}
do {
path.scope.crawl();
count = 0;
path.traverse({
VariableDeclarator(variablePath) {
if (variablePath.node.id.type === "Identifier") {
const local = variablePath.get("id");
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
variablePath.remove();
}
} else if (variablePath.node.id.type === "ObjectPattern") {
const pattern = variablePath.get("id");
const beforeCount = count;
const properties = pattern.get("properties");
properties.forEach(p => {
const local = p.get(
p.node.type === "ObjectProperty"
? "value"
: p.node.type === "RestElement"
? "argument"
: (() => {
throw new Error("invariant");
})(),
);
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
p.remove();
}
});
if (beforeCount !== count && pattern.get("properties").length < 1) {
variablePath.remove();
}
} else if (variablePath.node.id.type === "ArrayPattern") {
const pattern = variablePath.get("id");
const beforeCount = count;
const elements = pattern.get("elements");
elements.forEach(e => {
let local: NodePath<any> | undefined;
if (e.node && e.node.type === "Identifier") {
local = e;
} else if (e.node && e.node.type === "RestElement") {
local = e.get("argument");
} else {
return;
}
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
e.remove();
}
});
if (beforeCount !== count && pattern.get("elements").length < 1) {
variablePath.remove();
}
}
},
FunctionDeclaration: sweepFunction,
FunctionExpression: sweepFunction,
ArrowFunctionExpression: sweepFunction,
ImportSpecifier: sweepImport,
ImportDefaultSpecifier: sweepImport,
ImportNamespaceSpecifier: sweepImport,
});
} while (count);
},
},
},
};
}
export function treeShake(): Plugin {
let config: ResolvedConfig;
const cache: Record<string, any> = {};
let server: ViteDevServer;
async function transform(id: string, code: string) {
const [path, queryString] = id.split("?");
const query = new URLSearchParams(queryString);
if (query.has("pick")) {
const babel = await import("@babel/core");
const transformed = await babel.transformAsync(code, {
plugins: [[treeShakeTransform, { pick: query.getAll("pick") }]],
parserOpts: {
plugins: ["jsx", "typescript"],
},
filename: basename(id),
ast: false,
sourceMaps: true,
configFile: false,
babelrc: false,
sourceFileName: id,
});
return transformed;
}
}
return {
name: "tree-shake",
enforce: "pre",
configResolved(resolvedConfig) {
config = resolvedConfig;
},
configureServer(s) {
server = s;
},
async handleHotUpdate(ctx) {
if (cache[ctx.file]) {
const mods = [];
const newCode = await ctx.read();
for (const [id, code] of Object.entries(cache[ctx.file])) {
const transformed = await transform(id, newCode);
if (!transformed) continue;
const { code: transformedCode } = transformed;
if (transformedCode !== code) {
const mod = server.moduleGraph.getModuleById(id);
if (mod) mods.push(mod);
}
cache[ctx.file] ??= {};
cache[ctx.file][id] = transformedCode;
// server.moduleGraph.setModuleSource(id, code);
}
return mods;
}
// const mods = [];
// [...server.moduleGraph.urlToModuleMap.entries()].forEach(([url, m]) => {
// if (m.file === ctx.file && m.id.includes("pick=")) {
// if (!m.id.includes("pick=loader")) {
// mods.push(m);
// }
// }
// });
// return mods;
// // this.router.updateRoute(ctx.path);
// }
},
async transform(code, id) {
const [path, queryString] = id.split("?");
if (!path) return;
const query = new URLSearchParams(queryString);
const ext = path.split(".").pop();
if (!ext) return;
if (query.has("pick") && ["js", "jsx", "ts", "tsx"].includes(ext)) {
const transformed = await transform(id, code);
if (!transformed?.code) return;
cache[path] ??= {};
cache[path][id] = transformed.code;
return {
code: transformed.code,
map: transformed.map,
};
}
},
};
}