-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (39 loc) · 1.26 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
const { createFilter } = require('@rollup/pluginutils');
const MagicString = require('magic-string');
module.exports = function({ include, exclude, optimizeHref = false } = {}) {
const filter = createFilter(include, exclude);
return {
transform(code, id) {
if (!filter(id)) {
return;
}
const matches = [...code.matchAll(/new URL\((?:'|")([^'"]+)(?:'|"),\s*import\.meta\.url\)(\.href)?/g)];
if (matches.length) {
const s = new MagicString(code);
const imported = [];
for (const match of matches) {
const start = match.index;
const [str, pathname, href = ''] = match;
const varName = '__' + pathname.replace(/\W/g, '_') + '__';
if (!imported[varName]) {
s.prepend(`import ${varName} from "${pathname}";\n`);
imported[varName] = true;
}
s.overwrite(
start,
start + str.length,
href && optimizeHref
? varName
: `new URL(${varName}, import.meta.url || document.baseURI || self.location.href)${href}`
);
}
return {
code: s.toString(),
map: s.generateMap({ source: id })
}
} else {
return;
}
}
};
};