forked from unjs/magicast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vite.ts
108 lines (93 loc) · 2.53 KB
/
vite.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
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
import type { ProxifiedFunctionCall, ProxifiedModule } from "../proxy/types";
import { builders } from "../builders";
import { getDefaultExportOptions } from "./config";
import { deepMergeObject } from "./deep-merge";
export interface AddVitePluginOptions {
/**
* The import path of the plugin
*/
from: string;
/**
* The import name of the plugin
* @default "default"
*/
imported?: string;
/**
* The name of local variable
*/
constructor: string;
/**
* The options of the plugin
*/
options?: Record<string, any>;
/**
* The index in the plugins array where the plugin should be inserted at.
* By default, the plugin is appended to the array.
*/
index?: number;
}
export interface UpdateVitePluginConfigOptions {
/**
* The import path of the plugin
*/
from: string;
/**
* The import name of the plugin
* @default "default"
*/
imported?: string;
}
export function addVitePlugin(
magicast: ProxifiedModule<any>,
plugin: AddVitePluginOptions
) {
const config = getDefaultExportOptions(magicast);
const insertionIndex = plugin.index ?? config.plugins?.length ?? 0;
config.plugins ||= [];
config.plugins.splice(
insertionIndex,
0,
plugin.options
? builders.functionCall(plugin.constructor, plugin.options)
: builders.functionCall(plugin.constructor)
);
magicast.imports.$add({
from: plugin.from,
local: plugin.constructor,
imported: plugin.imported || "default",
});
return true;
}
export function findVitePluginCall(
magicast: ProxifiedModule<any>,
plugin: UpdateVitePluginConfigOptions | string
): ProxifiedFunctionCall | undefined {
const _plugin =
typeof plugin === "string" ? { from: plugin, imported: "default" } : plugin;
const config = getDefaultExportOptions(magicast);
const constructor = magicast.imports.$items.find(
(i) =>
i.from === _plugin.from && i.imported === (_plugin.imported || "default")
)?.local;
return config.plugins?.find(
(p: any) => p && p.$type === "function-call" && p.$callee === constructor
);
}
export function updateVitePluginConfig(
magicast: ProxifiedModule<any>,
plugin: UpdateVitePluginConfigOptions | string,
handler: Record<string, any> | ((args: any[]) => any[])
) {
const item = findVitePluginCall(magicast, plugin);
if (!item) {
return false;
}
if (typeof handler === "function") {
item.$args = handler(item.$args);
} else if (item.$args[0]) {
deepMergeObject(item.$args[0], handler);
} else {
item.$args[0] = handler;
}
return true;
}