Created
June 20, 2018 14:54
-
-
Save goloveychuk/ae19e7aab60f7ae5d3676fd90536d8c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as ts from "typescript"; | |
const path = require("path"); | |
function rstrip(str: string, strip: string) { | |
let ind = str.lastIndexOf(strip); | |
if (ind === str.length - strip.length) { | |
return str.slice(0, str.length - strip.length); | |
} | |
return str; | |
} | |
// function clean(resModule: ts.ResolvedModuleFull) { | |
// let stripped = rstrip(resModule.resolvedFileName, resModule.extension) | |
// } | |
function createVisitor( | |
program: ts.Program, | |
ctx: ts.TransformationContext, | |
sf: ts.SourceFile | |
) { | |
function visitImportClause(node: ts.ImportDeclaration) { | |
const moduleName = (<ts.StringLiteral>node.moduleSpecifier).text; | |
const host = ts.createCompilerHost(program.getCompilerOptions()); | |
// let a = (<any>ctx).getEmitResolver().getExternalModuleFileFromDeclaration(node) as ts.SourceFile | |
// if (moduleName.startsWith('app')) { | |
const resModule = (<any>ts).getResolvedModule(sf, moduleName) as | |
| ts.ResolvedModuleFull | |
| undefined; | |
// console.log(ts.getModuleSpecifier) | |
if (resModule === undefined || resModule.isExternalLibraryImport) { | |
return node; | |
} | |
// console.log() | |
let newModuleName = rstrip(resModule.resolvedFileName, resModule.extension); | |
// if (!moduleName.endsWith("index")) { | |
newModuleName = rstrip(newModuleName, "index"); | |
// } | |
// if (moduleName.startsWith('./')) { | |
// console.log(sf.fileName, newModuleName, moduleName, path.relative( sf.fileName, '../'), newModuleName) | |
// process.exit(0) | |
// } | |
newModuleName = path.relative(sf.fileName, newModuleName); | |
if (moduleName === newModuleName) { | |
return node; | |
} | |
console.log(moduleName, newModuleName); | |
return node; //todo replace | |
} | |
const visitor = (node: ts.Node): ts.VisitResult<ts.Node> => { | |
switch (node.kind) { | |
case ts.SyntaxKind.ImportDeclaration: | |
return visitImportClause(<ts.ImportDeclaration>node); | |
default: | |
return ts.visitEachChild(node, visitor, ctx); | |
} | |
}; | |
return visitor; | |
} | |
export default function(program: ts.Program) { | |
return (ctx: ts.TransformationContext): ts.Transformer<ts.SourceFile> => { | |
return (source: ts.SourceFile) => { | |
return ts.visitNode(source, createVisitor(program, ctx, source)); | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment