简体   繁体   English

Acorn - 为什么箭头 function 会引发解析错误?

[英]Acorn - why arrow function throws parsing error?

I'm trying to parse old React component source code with Acorn.我正在尝试用 Acorn 解析旧的 React 组件源代码。

Component to parse (ProjectNew2.js):要解析的组件(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);

any my JavaScript code:任何我的 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)

and exception:和例外:

SyntaxError: Unexpected token (21:22) SyntaxError:意外的令牌 (21:22)

Question: why Acorn throws an exception while parses arrow function?问题:为什么 Acorn 在解析箭头 function 时会抛出异常?

When I change parse to:当我将解析更改为:

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

Acorn parses it successfully. Acorn 成功解析它。

I believe the problem you are having is that class fields are a stage 3 proposal before the TC 39 and not yet part of the Javascript language (even if browsers already support them).我相信您遇到的问题是 class 字段是 TC 39 之前的第 3 阶段提案,还不是 Javascript 语言的一部分(即使浏览器已经支持它们)。 Much like with JSX you will probably need the appropriate parser plugin to parse them.就像 JSX 一样,您可能需要适当的解析器插件来解析它们。 This almost certainly has nothing to do with arrow functions, you could likely write class Foo { x = 'x' } and get the same error.这几乎可以肯定与箭头函数无关,您可能会编写class Foo { x = 'x' }并得到相同的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM