Created
April 19, 2018 19:29
-
-
Save kisenka/8082fad14ded8fee5233c306997c37e8 to your computer and use it in GitHub Desktop.
TypeScript transformer to rename imports (like babel-plugin-import-rename)
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
const ts = require('typescript'); | |
const IMPORT_RE = /(.*)\.pcss$/; | |
const REPLACE_TO = '$1.css'; | |
module.exports = function () { | |
return function (context) { | |
function visitor(node) { | |
const isImport = ts.isImportDeclaration(node); | |
const moduleName = isImport && node.moduleSpecifier ? node.moduleSpecifier.text : null; | |
const match = moduleName && IMPORT_RE.test(moduleName); | |
IMPORT_RE.lastIndex = 0; | |
if (!match) { | |
return ts.visitNodes(node, visitor, context); | |
} | |
return ts.createImportDeclaration( | |
undefined, | |
undefined, | |
undefined, | |
ts.createLiteral(moduleName.replace(IMPORT_RE, REPLACE_TO)), | |
); | |
} | |
return function transform(sourceFile) { | |
return ts.visitEachChild(sourceFile, visitor, context) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment