Search code examples
javascriptacorn

Acorn - why arrow function throws parsing error?


I'm trying to parse old React component source code with Acorn.

Component to parse (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:

#!/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)

Question: why Acorn throws an exception while parses arrow function?

When I change parse to:

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

Acorn parses it successfully.


Solution

  • 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). Much like with JSX you will probably need the appropriate parser plugin to parse them. This almost certainly has nothing to do with arrow functions, you could likely write class Foo { x = 'x' } and get the same error.