/
lib.ts
89 lines (81 loc) · 2.33 KB
/
lib.ts
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
84
85
86
87
88
89
const commonJSRegex: RegExp = /\b(module\.exports|exports\.\w+|exports\s*=\s*|exports\s*\[.*\]\s*=\s*)/;
const requireRegex: RegExp = /(?<!\.)\b_{0,2}require\s*\(\s*(["'`].*?["'`])\s*\)/g;
const IMPORT_STRING_PREFIX: String = "__require_for_vite";
const multilineCommentsRegex = /\/\*(.|[\r\n])*?\*\//gm
const singleCommentsRegex = /([^\:])\/\/.*/g
export interface TransformRequireResult {
code: string;
replaced: boolean;
}
export function transformRequire(code: string, id: string): TransformRequireResult {
let replaced = false;
// skip if has no require
if (!/require/.test(code)) {
return {
replaced,
code,
};
}
// empty multiline comments
code = removeComments(code, multilineCommentsRegex, '/* */');
// remove singleline comments
code = removeComments(code, singleCommentsRegex);
const requireMatches = code.matchAll(requireRegex);
let importsString = '';
let packageName = '';
for (let item of requireMatches) {
if (!isString(item[1])) {
console.warn(`Not supported dynamic import, file:${id}`);
continue;
}
replaced = true;
packageName = `${IMPORT_STRING_PREFIX}_${randomString(6)}`;
importsString += `import * as ${packageName} from ${item[1].replace(/`/g, `'`)};\n`;
code = code.replace(item[0], `(${packageName}.default || ${packageName})`);
}
if (replaced) {
code = importsString + code;
}
return {
replaced,
code,
};
}
export function isCommonJS(code: string): boolean {
return commonJSRegex.test(code);
}
function removeComments(
code: string,
exp: RegExp,
replaceValue?: string
): string {
const matches = code.matchAll(exp);
let matcheStr: string;
for (let item of matches) {
matcheStr = item[0];
if (matcheStr.search(requireRegex) == -1) {
continue;
}
if (!replaceValue) {
replaceValue = item[1] || '';
}
code = code.replace(matcheStr, replaceValue);
}
return code;
}
function randomString(length: number): string {
const code: string =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
let result: string = "";
for (let index = 0; index < length; index++) {
result += code[Math.floor(Math.random() * code.length)];
}
return result;
}
function isString(text: string) {
try {
return typeof eval(text) === "string";
} catch (err) {
return false;
}
}