forked from Kitware/vtk-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin-rewrite-filenames.js
52 lines (48 loc) · 1.49 KB
/
plugin-rewrite-filenames.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
import MagicString from 'magic-string';
/**
* find: RegExp | String
* replace: String
*/
/* eslint-disable import/prefer-default-export */
export function rewriteFilenames(pluginOptions) {
const opts = {
...pluginOptions,
find: new RegExp(pluginOptions.find),
};
return {
name: 'rewrite-filenames',
generateBundle(outputOptions, bundle, isWrite) {
const files = Object.keys(bundle);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const info = bundle[file];
if (opts.find.test(file)) {
const newFileName = file.replace(opts.find, opts.replace);
info.fileName = newFileName;
bundle[newFileName] = info;
delete bundle[file];
}
// search contents for offending import filenames
const importRe = new RegExp(
'(import .+? from\\s*["\'])(.+?)(["\']\\s*;?)',
'g'
);
let match;
do {
match = importRe.exec(info.code);
if (match) {
const target = match[2];
const start = match.index + match[1].length;
const end = start + target.length;
if (opts.find.test(target)) {
const magicCode = new MagicString(info.code);
const newTarget = target.replace(opts.find, opts.replace);
magicCode.overwrite(start, end, newTarget);
info.code = magicCode.toString();
}
}
} while (match);
}
},
};
}