Acorn - 为什么箭头函数会抛出解析错误?

Acorn - why arrow function throws parsing error?

我正在尝试用 Acorn 解析旧的 React 组件源代码。

要解析的组件(ProjectNew2.js):

import React from 'react';

class ProjectNew extends React.Component {

    componentDidMount = () => {
        // do some stuff here...
    }

    render() {
        return (
            <div>fooo</div>
        );
    }

}

export default connect(mapStateToProps)(ProjectNew);

任何我的 JavaScript 代码:

#!/usr/bin/env node

const Fs = require('fs')
const acorn = require("acorn")
const jsx = require("acorn-jsx")

let fileName = "./ProjectNew2.js";
let cnt = Fs.readFileSync(fileName).toString()

let s = acorn.Parser.extend(jsx()).parse(cnt, {ecmaVersion: "latest", sourceType: "module"});

console.log(s)

和异常:

SyntaxError: Unexpected token (21:22)

问题:为什么Acorn在解析箭头函数时抛出异常?

当我将解析更改为:

componentDidMount(){
    // do some stuff here...
}

Acorn 解析成功。

我认为您遇到的问题是 class 字段需要 stage 3 proposal before the TC 39 and not yet part of the Javascript language (even if browsers already support them). Much like with JSX you will probably need the appropriate parser plugin 来解析它们。这几乎肯定与箭头函数无关,您可能会写 class Foo { x = 'x' } 并得到相同的错误。