5

我试图玩 babel 模块babylon,,,babel-traverse。当我试图替换一个节点时,程序崩溃了Maximum call stack size exceeded。这是我的代码

import * as babylon from 'babylon'
import traverse from 'babel-traverse'
import generate from 'babel-generator'
import * as t from 'babel-types'


const code = `
import a from 'b'
n === 3
`
const ast = babylon.parse(code, {
  sourceType: 'module'
})

const visitor = {
  BinaryExpression(path) {
    console.log((path.node))
    path.replaceWith(t.binaryExpression('**', t.numericLiteral(3), t.numericLiteral(4)))
  }
}

traverse(ast, visitor)

let generated = generate(ast, null, code)
console.log(generated.code)

我正在使用下面的 babel 依赖项,知道吗?

"dependencies": {
"babel-generator": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-traverse": "^6.9.0",
"babel-types": "^6.9.1",
"babylon": "^6.8.0"
}
4

2 回答 2

5

您收到堆栈错误的原因是您的二进制表达式替换会生成另一个二进制表达式。您的替换二进制表达式一遍又一遍地输入到访问者中,无穷无尽。

要打破无限循环,您需要检查您的替换是否已经发生,可能replaceWith在您看到运算符时忽略该步骤 is **

于 2016-11-13T16:41:04.607 回答
3

在 BinaryExpression 上有访问者时添加新的 binaryExpression 会导致访问新的 binaryExpression,因此这是一个无限循环。您可以调用path.skipafterpath.replaceWith跳过访问新表达式。

path.replaceWith(t.binaryExpression('**', t.numericLiteral(3), t.numericLiteral(4)))
path.skip()
于 2020-05-18T17:06:38.090 回答