This repository has been archived by the owner on Aug 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
83 lines (66 loc) · 1.99 KB
/
index.js
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
import MagicString from 'magic-string';
import { createFilter } from 'rollup-pluginutils';
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
function ensureFunction(functionOrValue) {
if (typeof functionOrValue === 'function') return functionOrValue;
return () => functionOrValue;
}
function longest(a, b) {
return b.length - a.length;
}
function getReplacements(options) {
if (options.values) {
return Object.assign({}, options.values);
} else {
const values = Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
delete values.sourcemap;
delete values.sourceMap;
return values;
}
}
function mapToFunctions(object) {
return Object.keys(object).reduce((functions, key) => {
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}
export default function replace(options = {}) {
const filter = createFilter(options.include, options.exclude);
const { delimiters } = options;
const functionValues = mapToFunctions(getReplacements(options));
const keys = Object.keys(functionValues)
.sort(longest)
.map(escape);
const pattern = delimiters
? new RegExp(`${escape(delimiters[0])}(${keys.join('|')})${escape(delimiters[1])}`, 'g')
: new RegExp(`\\b(${keys.join('|')})\\b`, 'g');
return {
name: 'replace',
transform(code, id) {
if (!filter(id)) return null;
const magicString = new MagicString(code);
let hasReplacements = false;
let match;
let start;
let end;
let replacement;
while ((match = pattern.exec(code))) {
hasReplacements = true;
start = match.index;
end = start + match[0].length;
replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
if (!hasReplacements) return null;
const result = { code: magicString.toString() };
if (options.sourceMap !== false && options.sourcemap !== false)
result.map = magicString.generateMap({ hires: true });
return result;
}
};
}