如何用刚刚解析的javascript(字符串)替换AST中的路径?

use*_*582 6 abstract-syntax-tree jscodeshift codemod

https://astexplorer.net/#/gist/70df1bc56b9ee73d19fc949d2ef829ed/7e14217fd8510f0bf83f3372bf08454b7617bce1

我现在发现我正在尝试replace表达,我不在乎它是什么.

在这个例子中我发现了this.state.showMenu && this.handleMouseDown部分

<a
  onMouseDown={this.state.showMenu && this.handleMouseDown}
>
Run Code Online (Sandbox Code Playgroud)

我需要转换为:

<a
  onMouseDown={this.state.showMenu ? this.handleMouseDown : undefined}
>
Run Code Online (Sandbox Code Playgroud)

如何在不明确重建树的情况下这样做?我只是想做点什么

path.replaceText("this.state.showMenu ? this.handleMouseDown : undefined")
Run Code Online (Sandbox Code Playgroud)

bgr*_*ran 3

这是一个可以执行您所描述的操作的变压器:

export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source)

  root
    .find(j.JSXExpressionContainer)
    .replaceWith(path => {
        return j.jsxExpressionContainer(
            j.conditionalExpression(
                j.identifier(j(path.value.expression.left).toSource()),
                j.identifier(j(path.value.expression.right).toSource()),
                j.identifier('undefined')
            )
        )
    })

  return root.toSource()
}
Run Code Online (Sandbox Code Playgroud)

在这里查看它的实际效果。

您还可以在节点中放置任意文本JSXExpressionContainer

export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source)

  root
    .find(j.JSXExpressionContainer)
    .replaceWith(path => {
        return j.jsxExpressionContainer(
            j.identifier('whatever you want')
        )
    })

  return root.toSource()
}
Run Code Online (Sandbox Code Playgroud)

请参阅此示例

最后,您甚至不需要返回JSXExpressionContainer.

export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source)

  root
    .find(j.JSXExpressionContainer)
    .replaceWith(path => {
        return j.identifier("this isn't valid JS, but works just fine")
    })

  return root.toSource()
}
Run Code Online (Sandbox Code Playgroud)

在这里查看结果。