-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpostprocess.js
More file actions
41 lines (36 loc) · 1.13 KB
/
postprocess.js
File metadata and controls
41 lines (36 loc) · 1.13 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
import MagicString from 'magic-string';
let currentToken;
const replacer = (str, index) => currentToken[index];
export default function postprocess(allReplacements) {
return {
name: 'postprocess',
transformBundle(code, { sourceMap, format }) {
let str = new MagicString(code);
let replacements = typeof allReplacements==='function' ? allReplacements({ code, sourceMap, format }) : allReplacements;
for (let i=0; i<replacements.length; i++) {
let [find, replace=''] = replacements[i];
if (typeof find==='string') find = new RegExp(find);
if (!find.global) {
find = new RegExp(find.source, 'g' + String(find).split('/').pop());
}
let token;
while (token=find.exec(code)) {
let value;
if (typeof replace==='function') {
value = replace.apply(null, token);
if (value==null) value = '';
}
else {
currentToken = token;
value = replace.replace(/\$(\d+)/, replacer);
}
str.overwrite(token.index, token.index + token[0].length, value);
}
}
return {
code: str.toString(),
map: sourceMap===false ? null : str.generateMap({ hires: true })
};
}
};
}