-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathts-alias.js
94 lines (86 loc) · 2.69 KB
/
ts-alias.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
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
90
91
92
93
94
const {
existsSync,
statSync,
readdirSync,
readFileSync,
writeFileSync,
} = require('fs');
const { dirname, join, relative, resolve, extname } = require('path');
const tsConfig = require('../tsconfig.json');
const tsConfigServer = require('../server/tsconfig.json');
if (
!tsConfig.compilerOptions.paths ||
Object.keys(tsConfig.compilerOptions.paths).length === 0
) {
console.log('No paths defined');
return;
}
const basePath = resolve(
join(__dirname, '..', tsConfig.compilerOptions.baseUrl)
);
const distPath = join(
basePath,
'server',
tsConfigServer.compilerOptions.outDir
);
let aliasesFixed = 0;
const jsFiles = getJsFiles(distPath);
jsFiles.forEach(replaceAliases.bind(undefined, tsConfig.compilerOptions.paths));
console.log(`${aliasesFixed} TS aliases replaced in ${jsFiles.length} files`);
function getJsFiles(baseFolder, list = []) {
readdirSync(baseFolder).forEach((filename) => {
const fullPath = join(baseFolder, filename);
if (statSync(fullPath).isDirectory()) {
return getJsFiles(fullPath, list);
}
if (extname(fullPath) !== '.js') return;
list.push(fullPath);
});
return list;
}
function replaceAliases(paths, filePath) {
const code = readFileSync(filePath).toString();
const rel = relative(dirname(filePath), distPath).replace(/\\/g, '/');
const newCode = Object.entries(paths).reduce(
(replacedCode, [alias, targets]) => {
if (alias.substr(-2, 2) === '/*') {
// relative import
const aliasFolder = alias.substr(0, alias.length - 2);
const re = new RegExp(
`= require\\(["']${aliasFolder}/([^"']+)["']\\)`,
'g'
);
return replacedCode.replace(re, (match, path) => {
for (const target of targets) {
const targetFile = `${target.substr(0, target.length - 2)}/${path}`;
const targetPath = join(dirname(filePath), rel, targetFile);
if (!existFile(targetPath)) continue;
aliasesFixed++;
return `= require("${rel}/${targetFile}")`;
}
return match;
});
} else {
// exact import
const re = new RegExp(`= require\\(["']${alias}["']\\)`, 'g');
return replacedCode.replace(re, (match) => {
for (const target of targets) {
const targetPath = join(dirname(filePath), rel, target);
if (!existFile(targetPath)) continue;
aliasesFixed++;
return `= require("${rel}/${target}")`;
}
return match;
});
}
},
code
);
writeFileSync(filePath, newCode);
}
function existFile(filePath) {
return (
existsSync(filePath) ||
existsSync(`${filePath}.js` || `${filePath}/index.js`)
);
}