35 lines
1.1 KiB
JavaScript
35 lines
1.1 KiB
JavaScript
import fs from 'fs';
|
|
import path from 'path';
|
|
const rootDir = process.cwd();
|
|
const config = JSON.parse(fs.readFileSync('jsconfig.json', 'utf-8'));
|
|
const { paths, baseUrl } = config.compilerOptions;
|
|
|
|
function resolveImportPath(importPath, fileBase) {
|
|
if (!importPath) return null;
|
|
importPath = jsConfigPaths(importPath);
|
|
const fileDir = path.dirname(fileBase);
|
|
if (importPath.startsWith('.') || importPath.startsWith('/')) {
|
|
return path.relative(rootDir, path.resolve(fileDir, importPath));
|
|
}
|
|
|
|
return importPath;
|
|
}
|
|
function toRelative(file) {
|
|
return path.relative(rootDir, file);
|
|
}
|
|
|
|
function jsConfigPaths(importPath) {
|
|
for (const [aliasPattern, [target]] of Object.entries(paths)) {
|
|
const alias = aliasPattern.replace('/*', '');
|
|
const targetBase = target.replace('/*', '');
|
|
|
|
if (importPath.startsWith(alias)) {
|
|
const rest = importPath.slice(alias.length);
|
|
return path.resolve(baseUrl, targetBase + rest);
|
|
}
|
|
}
|
|
return importPath;
|
|
}
|
|
|
|
export { resolveImportPath, toRelative };
|