Skip to content

Commit

Permalink
Parse w/ recast directly in the transform
Browse files Browse the repository at this point in the history
This is necessary to conditionally include the 'jsx' babylon plugin
when transforming a .tsx file. See also:
facebook/jscodeshift#180 (comment)
  • Loading branch information
elliottsj committed Apr 6, 2018
1 parent 88e3e3a commit 04b0e80
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 22 deletions.
18 changes: 12 additions & 6 deletions transforms/__tests__/reverse-identifiers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@

const transform = require('../reverse-identifiers');
const defineInlineTest = require('jscodeshift/dist/testUtils').defineInlineTest;
const runInlineTest = require('jscodeshift/dist/testUtils').runInlineTest;

defineInlineTest(
transform,
{},
'let foo: string = ""',
'let oof: string = ""'
);
it('transforms correctly', () => {
runInlineTest(
transform,
{},
{
path: 'source.ts',
source: 'let foo: string = <string>"somestring"',
},
'let oof: string = <string>"somestring"',
);
});
28 changes: 12 additions & 16 deletions transforms/reverse-identifiers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,30 @@
*/

const babylon = require('babylon');
const recast = require('recast');

/**
* Example jscodeshift transformer. Simply reverses the names of all
* identifiers. Stolen from:
* https://github.com/facebook/jscodeshift/blob/7be2557f369794e915afe7f91ab81b1215e66857/sample/reverse-identifiers.js
*/
function transform(file, api) {
const parse = source => babylon.parse(source, {
sourceType: 'module',
plugins: file.path.endsWith('.tsx') ? ['jsx', 'typescript'] : ['typescript'],
});

const j = api.jscodeshift;

return j(file.source)
return j(recast.parse(file.source, { parser: { parse } }))
.find(j.Identifier)
.replaceWith(
p => {
return {
...j.identifier(p.node.name.split('').reverse().join('')),
typeAnnotation: p.value.typeAnnotation
};
}
p => ({
...p.node,
name: p.node.name.split('').reverse().join('')
})
)
.toSource();
}

module.exports = transform;
module.exports.parser = {
parse: source => babylon.parse(source, {
sourceType: 'module',
plugins: [
'typescript'
],
}),
};

0 comments on commit 04b0e80

Please sign in to comment.