Skip to content

Instantly share code, notes, and snippets.

@nsfmc
Last active February 24, 2016 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsfmc/8a54414a06a325a04bbe to your computer and use it in GitHub Desktop.
Save nsfmc/8a54414a06a325a04bbe to your computer and use it in GitHub Desktop.
change jsx requires to require extension-less version
/**
* jsx-require-codeshift changes all import/require calls for .jsx files to their root files
*
* this is not a very complicated jscodeshift transform, but the more the merrier imo, since there
* aren't very many out there to peek at. (it could probably be satisfied with a not-crazy regex).
*
* What this does is converts calls like `import Foo from 'foo.jsx';` to `import Foo from 'foo';`
* and similarly, it also converts require calls for jsx files to their extensionless versions.
*
*/
export default function transformer(file, api) {
const j = api.jscodeshift;
var importMod = j(file.source)
.find(j.ImportDeclaration)
.replaceWith(function(p) {
var reqstring = p.node.source.value;
if(reqstring.endsWith('jsx'))
return j.importDeclaration(p.node.specifiers,j.literal(reqstring.split('.jsx')[0]))
return p.node
})
.toSource({quote: 'single'});
var requireMod = j(importMod)
.find(j.CallExpression, {callee: {name: 'require'}})
.replaceWith(function(p) {
var reqstring = p.node.arguments[0].value
if(reqstring.endsWith('jsx'))
return j.callExpression(j.identifier('require'), [j.literal(reqstring.split('.jsx')[0])])
return p.node
}
).toSource({quote: 'single'});
return requireMod;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment