From 04b0e80d4eaa5ac22da25e0a7954f988737d776a Mon Sep 17 00:00:00 2001 From: Spencer Elliott Date: Thu, 5 Apr 2018 22:57:56 -0700 Subject: [PATCH] Parse w/ recast directly in the transform This is necessary to conditionally include the 'jsx' babylon plugin when transforming a .tsx file. See also: https://github.com/facebook/jscodeshift/issues/180#issuecomment-364850503 --- transforms/__tests__/reverse-identifiers.js | 18 ++++++++----- transforms/reverse-identifiers.js | 28 +++++++++------------ 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/transforms/__tests__/reverse-identifiers.js b/transforms/__tests__/reverse-identifiers.js index 3afe177..c462de6 100644 --- a/transforms/__tests__/reverse-identifiers.js +++ b/transforms/__tests__/reverse-identifiers.js @@ -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 = "somestring"', + }, + 'let oof: string = "somestring"', + ); +}); diff --git a/transforms/reverse-identifiers.js b/transforms/reverse-identifiers.js index 215273c..a4cc1ba 100644 --- a/transforms/reverse-identifiers.js +++ b/transforms/reverse-identifiers.js @@ -8,6 +8,7 @@ */ const babylon = require('babylon'); +const recast = require('recast'); /** * Example jscodeshift transformer. Simply reverses the names of all @@ -15,27 +16,22 @@ const babylon = require('babylon'); * 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' - ], - }), -};