0

给定代码片段,包括一个 React 组件的简单 tsx 字符串:

// 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());

当使用节点执行该文件时,ts-node test.ts会出现如下错误:

.../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)
...

如何使用这些j选项来使用成功解析.tsx代码的解析器?

我期待类似的东西

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

但到目前为止我无法让它工作

4

1 回答 1

0

显然,一种可能性是使用 babel 解析器和一些插件

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
                },
            }),
    });

这段代码主要抄自 egghead.io 文章https://egghead.io/blog/codemods-with-babel-plugins

于 2021-12-23T14:42:14.640 回答