forked from vitejs/rolldown-vite
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatchCJS.ts
64 lines (43 loc) · 1.3 KB
/
patchCJS.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
/**
It converts
```ts
exports.default = vuePlugin;
exports.parseVueRequest = parseVueRequest;
```
to
```ts
module.exports = vuePlugin;
module.exports.default = vuePlugin;
module.exports.parseVueRequest = parseVueRequest;
```
*/
import { readFileSync, writeFileSync } from "node:fs";
import colors from "picocolors";
const indexPath = "dist/index.cjs";
let code = readFileSync(indexPath, "utf-8");
const matchMixed = code.match(/\nexports.default = (\w+);/);
if (matchMixed) {
const name = matchMixed[1];
const lines = code.trimEnd().split("\n");
// search from the end to prepend `modules.` to `export[xxx]`
for (let i = lines.length - 1; i > 0; i--) {
if (lines[i].startsWith("exports")) lines[i] = "module." + lines[i];
else {
// at the beginning of exports, export the default function
lines[i] += `\nmodule.exports = ${name};`;
break;
}
}
writeFileSync(indexPath, lines.join("\n"));
console.log(colors.bold(`${indexPath} CJS patched`));
process.exit(0);
}
const matchDefault = code.match(/\nmodule.exports = (\w+);/);
if (matchDefault) {
code += `module.exports.default = ${matchDefault[1]};\n`;
writeFileSync(indexPath, code);
console.log(colors.bold(`${indexPath} CJS patched`));
process.exit(0);
}
console.error(colors.red(`${indexPath} CJS patch failed`));
process.exit(1);