-
-
Notifications
You must be signed in to change notification settings - Fork 599
/
Copy pathindex.ts
executable file
·101 lines (88 loc) · 2.8 KB
/
index.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
import { Plugin } from 'rollup';
import { ResolvedAlias, ResolverFunction, ResolverObject, RollupAliasOptions } from '../types';
function matches(pattern: string | RegExp, importee: string) {
if (pattern instanceof RegExp) {
return pattern.test(importee);
}
if (importee.length < pattern.length) {
return false;
}
if (importee === pattern) {
return true;
}
// eslint-disable-next-line prefer-template
return importee.startsWith(pattern + '/');
}
function getEntries({ entries, customResolver }: RollupAliasOptions): readonly ResolvedAlias[] {
if (!entries) {
return [];
}
const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
if (Array.isArray(entries)) {
return entries.map((entry) => {
return {
find: entry.find,
replacement: entry.replacement,
resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
};
});
}
return Object.entries(entries).map(([key, value]) => {
return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
});
}
function resolveCustomResolver(
customResolver: ResolverFunction | ResolverObject | null | undefined
): ResolverFunction | null {
if (customResolver) {
if (typeof customResolver === 'function') {
return customResolver;
}
if (typeof customResolver.resolveId === 'function') {
return customResolver.resolveId;
}
}
return null;
}
export default function alias(options: RollupAliasOptions = {}): Plugin {
const entries = getEntries(options);
if (entries.length === 0) {
return {
name: 'alias',
resolveId: () => null
};
}
return {
name: 'alias',
async buildStart(inputOptions) {
await Promise.all(
[...(Array.isArray(options.entries) ? options.entries : []), options].map(
({ customResolver }) =>
customResolver &&
typeof customResolver === 'object' &&
typeof customResolver.buildStart === 'function' &&
customResolver.buildStart.call(this, inputOptions)
)
);
},
resolveId(importee, importer, resolveOptions) {
if (!importer) {
return null;
}
// First match is supposed to be the correct one
const matchedEntry = entries.find((entry) => matches(entry.find, importee));
if (!matchedEntry) {
return null;
}
const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
if (matchedEntry.resolverFunction) {
return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
}
return this.resolve(
updatedId,
importer,
Object.assign({ skipSelf: true }, resolveOptions)
).then((resolved) => resolved || { id: updatedId });
}
};
}