-
Notifications
You must be signed in to change notification settings - Fork 0
/
convertEsmToCjs.ts
62 lines (47 loc) · 1.82 KB
/
convertEsmToCjs.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
/**
* @file Creates CJS files from each JS file in the directories.
*/
// @ts-expect-error
import * as nodeFs from 'node:fs';
// @ts-expect-error
import * as nodePath from 'node:path';
// @ts-expect-error
const nodeJsProcess = process as {argv: string[]};
const {readFileSync, readdirSync, writeFileSync} = nodeFs as {
readdirSync: (path: string, options?: {recursive?: boolean}) => readonly string[];
readFileSync: (path: string, options: {encoding: 'utf8'}) => string;
writeFileSync: (path: string, data: string) => void;
};
const {join} = nodePath as {join: (...paths: readonly string[]) => string};
const paths = nodeJsProcess.argv.slice(2);
/**
* Replaces `.js` file extension to `.cjs`.
*/
const replaceExtension = (fileName: string): string => fileName.replace('.js', '.cjs');
for (const path of paths) {
const fileNames = readdirSync(path, {recursive: true});
for (const fileName of fileNames) {
if (!fileName.endsWith('.js')) {
continue;
}
const filePath = join(path, fileName);
let fileContent = readFileSync(filePath, {encoding: 'utf8'});
fileContent = fileContent.replace(
/^import {([^}]+)} from ([^;]*);/gim,
(_match, names, modulePath) =>
`const {${names.replaceAll(' as ', ': ')}} = require(${replaceExtension(modulePath)});`,
);
fileContent = fileContent.replace(
/^export {([^}]+)} from ([^;]*);/gim,
(_match, names, modulePath) =>
`{\nconst {${names}} = require(${replaceExtension(modulePath)});\nObject.assign(exports, {${names}});\n};`,
);
fileContent = fileContent.replace(
/^export const ([^ ]+) /gim,
(_match, name) => `const ${name} = exports.${name} `,
);
fileContent = `'use strict';\n${fileContent}`;
const newFilePath = replaceExtension(filePath);
writeFileSync(newFilePath, fileContent);
}
}