Created
December 11, 2022 20:35
-
-
Save dansalias/01ab52390b2c6ca3f811cfb266ae9078 to your computer and use it in GitHub Desktop.
Rewrite TypeScript imports at compile time
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 ts from 'typescript' | |
const unpackImportPath = (node: ts.ImportDeclaration): string => { | |
const moduleSpecifier = node.moduleSpecifier as ts.StringLiteral | |
return moduleSpecifier.text | |
} | |
const transformImport = ( | |
factory: ts.NodeFactory, | |
node: ts.ImportDeclaration, | |
): ts.ImportDeclaration => { | |
return factory.updateImportDeclaration( | |
node, | |
node.modifiers, | |
node.importClause, | |
factory.createStringLiteral('NEW PATH GOES HERE'), | |
undefined, | |
) | |
} | |
const transformer: ts.TransformerFactory<ts.SourceFile> = (context) => { | |
const visitor: ts.Visitor = (node) => { | |
if (ts.isImportDeclaration(node)) { | |
return transformImport(context.factory, node) | |
} | |
return ts.visitEachChild(node, visitor, context) | |
} | |
return (sourceFile) => { | |
return ts.visitNode(sourceFile, visitor) | |
} | |
} | |
// using ts.transpileModule | |
const { | |
outputText, | |
diagnostics, | |
} = ts.transpileModule(`TS SOURCE CODE`, { | |
transformers: { after: [ transformer ] }, | |
compilerOptions: { | |
// ... | |
}, | |
}) | |
// using ts.createProgram | |
const program = ts.createProgram( | |
[ FILE_PATHS_GO_HERE ], | |
{ | |
// compilerOptions... | |
}, | |
) | |
program.emit( | |
undefined, | |
undefined, | |
undefined, | |
undefined, | |
{ | |
after: [ transformer ], | |
}, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment