Skip to content

Instantly share code, notes, and snippets.

@kisenka
Created April 19, 2018 19:29
Show Gist options
  • Save kisenka/8082fad14ded8fee5233c306997c37e8 to your computer and use it in GitHub Desktop.
Save kisenka/8082fad14ded8fee5233c306997c37e8 to your computer and use it in GitHub Desktop.
TypeScript transformer to rename imports (like babel-plugin-import-rename)
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