You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Esprima与Acorn解析普通函数报错:unexpected token '(' 求解决方案

解决Esprima/Acorn解析普通函数报错的问题

嘿,这个问题其实是JavaScript语法本身的规则导致的,不是解析器的问题哦!

错误原因

你写的function () { console.log('Test')}是匿名函数声明,但JavaScript的语法规范里,函数声明必须要有名称;而箭头函数属于函数表达式范畴,匿名是完全合法的,所以解析箭头函数没问题,解析匿名函数声明就会抛出语法错误。

解决办法

这里有两个靠谱的解决方向:

  • 改成函数表达式:把匿名函数作为表达式使用(比如赋值给变量,或者作为参数传递),这样解析器就能正确识别了:

    // 赋值给变量的函数表达式
    console.log(esprima.parseScript(`const fn = function () { console.log('Test')}`));
    console.log(acorn.parse(`const fn = function () { console.log('Test') }`));
    
    // 也可以写成立即执行函数表达式(IIFE)
    console.log(esprima.parseScript(`(function () { console.log('Test')})()`));
    
  • 给函数声明添加名称:如果你的场景确实需要用函数声明(而不是表达式),那必须给函数加上合法的名称:

    console.log(esprima.parseScript(`function testFn() { console.log('Test')}`));
    console.log(acorn.parse(`function testFn() { console.log('Test') }`));
    

顺便修正代码里的小bug

你提供的代码里,第二个acorn.parse的语句末尾少了一个闭合括号,修正后才不会报语法错误哦:

console.log(acorn.parse(` () => { console.log('Test') }`)); // 补上最后的括号

内容的提问来源于stack exchange,提问作者amp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:01:15