UNPKG

2.04 kBJavaScriptView Raw
1import MagicString from 'magic-string';
2import { createFilter } from 'rollup-pluginutils';
3
4function escape(str) {
5 return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
6}
7
8function ensureFunction(functionOrValue) {
9 if (typeof functionOrValue === 'function') return functionOrValue;
10 return () => functionOrValue;
11}
12
13function longest(a, b) {
14 return b.length - a.length;
15}
16
17function getReplacements(options) {
18 if (options.values) {
19 return Object.assign({}, options.values);
20 } else {
21 const values = Object.assign({}, options);
22 delete values.delimiters;
23 delete values.include;
24 delete values.exclude;
25 delete values.sourcemap;
26 delete values.sourceMap;
27 return values;
28 }
29}
30
31function mapToFunctions(object) {
32 return Object.keys(object).reduce((functions, key) => {
33 functions[key] = ensureFunction(object[key]);
34 return functions;
35 }, {});
36}
37
38export default function replace(options = {}) {
39 const filter = createFilter(options.include, options.exclude);
40 const { delimiters } = options;
41 const functionValues = mapToFunctions(getReplacements(options));
42 const keys = Object.keys(functionValues)
43 .sort(longest)
44 .map(escape);
45
46 const pattern = delimiters
47 ? new RegExp(`${escape(delimiters[0])}(${keys.join('|')})${escape(delimiters[1])}`, 'g')
48 : new RegExp(`\\b(${keys.join('|')})\\b`, 'g');
49
50 return {
51 name: 'replace',
52
53 transform(code, id) {
54 if (!filter(id)) return null;
55
56 const magicString = new MagicString(code);
57
58 let hasReplacements = false;
59 let match;
60 let start;
61 let end;
62 let replacement;
63
64 while ((match = pattern.exec(code))) {
65 hasReplacements = true;
66
67 start = match.index;
68 end = start + match[0].length;
69 replacement = String(functionValues[match[1]](id));
70
71 magicString.overwrite(start, end, replacement);
72 }
73
74 if (!hasReplacements) return null;
75
76 const result = { code: magicString.toString() };
77 if (options.sourceMap !== false && options.sourcemap !== false)
78 result.map = magicString.generateMap({ hires: true });
79
80 return result;
81 }
82 };
83}