How to parse React Typescript into jscodeshift code

1.6k views Asked by At

Given the code snippet, including a simple tsx string of a React component:

// test.ts

    import j from "jscodeshift";

    const code = `
    const words: string[] = ["hello", "world"];
    
    export default function(){
        return <div>{words.map(word => <span>{word}</span>)}</div>;
    }
    `;

    const ast = j(code);

    console.log(ast.toSource());

When that file is executed with node ts-node test.ts it errors like this:

.../jscodeshift/node_modules/@babel/parser/src/parser/error.js:97
    const err: SyntaxError & ErrorContext = new SyntaxError(message);
                                            ^
SyntaxError: Const declarations require an initialization value (1:11)
...

How can I use the j options to use a parser that successfully parses the .tsx code?

I expect something like

const ast = j(code, { parser: something, plugins: [somethingElse]});

But I couldn't make it work, so far

1

There are 1 answers

0
Soldeplata Saketos On

Apparently, one possibility is to use babel parser and some plugins

import { parseSync } from "@babel/core";
import j from "jscodeshift";

const ast = j(code, {
  parser: {
        parse: (source) =>
            parseSync(source, {
                plugins: [`@babel/plugin-syntax-jsx`, `@babel/plugin-proposal-class-properties`],
                overrides: [
                    {
                        test: [`**/*.ts`, `**/*.tsx`],
                        plugins: [[`@babel/plugin-syntax-typescript`, { isTSX: true }]],
                    },
                ],
                filename: "source-file.tsx", // this defines the loader depending on the extension
                parserOpts: {
                    tokens: true, // recast uses this
                },
            }),
    });

This code was mainly copied from egghead.io article https://egghead.io/blog/codemods-with-babel-plugins