forked from andreasbm/web-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollup-plugin-replace.ts
44 lines (37 loc) · 1.13 KB
/
rollup-plugin-replace.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
import colors from "colors";
import { resolve, parse } from "path";
import { ResolveIdResult } from "rollup";
export interface IRollupPluginReplaceConfig {
verbose: boolean;
resources: [string, string][];
}
const defaultConfig: IRollupPluginReplaceConfig = {
verbose: true,
resources: []
};
/**
* A Rollup plugin that replaces an import with another import.
* @param config
*/
export function replace(config: Partial<IRollupPluginReplaceConfig> = {}) {
const { resources, verbose } = { ...defaultConfig, ...config };
return {
name: "replace",
resolveId: (id: string, importer: string): ResolveIdResult | void => {
if (!importer) return;
const { name: idName } = parse(id);
for (const [from, to] of resources) {
if (from == null || to == null) return;
const { name: fromName } = parse(from);
// If the id and the from name are the same, we simply need to resolve
// it to the "to name" instead and we have replaced the file.
if (idName === fromName) {
if (verbose) {
console.log(colors.green(`[replace] - Replaced "${id}" with "${to}"\n`));
}
return resolve(to);
}
}
}
};
}