acornjs / acorn-jsx

Alternative, faster React.js JSX parser
MIT License
648 stars 72 forks source link

Parsing error when using class functions #88

Closed kariae closed 6 years ago

kariae commented 6 years ago

thanks for the amazing parser, I've got a Unexpected token (6:14) when I want to parse a component having a class function, here is the code for it

import React from "react";
import PropTypes from "prop-types";
import "./Button.css";

class Button extends React.Component {
  handleClick = () => {
    this.props.clickHandler(this.props.name);
  };

  render() {
    const className = [
      "component-button",
      this.props.orange ? "orange" : "",
      this.props.wide ? "wide" : "",
    ];

    return (
      <div className={className.join(" ").trim()}>
        <button onClick={this.handleClick}>{this.props.name}</button>
      </div>
    );
  }
}
Button.propTypes = {
  name: PropTypes.string,
  orange: PropTypes.bool,
  wide: PropTypes.bool,
  clickHandler: PropTypes.func,
};
export default Button;

any way to fix this, thanks?

RReverser commented 6 years ago

Sorry, you haven't provided the code you're trying to use for parsing, but acorn-jsx generally has nothing to do with regular JS syntax, it's plugin specifically for JSX. Maybe you didn't specify correct ecmaVersion in acorn options?

kariae commented 6 years ago

ah really sorry, just found the parser and I'm trying to figure it out, here is the code I use for parsing

const content = fs.readFileSync(file, { encoding: 'utf-8' })
    const ast = acorn.parse(content, {
        sourceType: 'module',
        plugins: { jsx: true },
    });

Did I miss something maybe?

RReverser commented 6 years ago

Then you need to check plugins at the bottom in https://github.com/acornjs/acorn README. Problem is, class A { x = 1 } like syntax is a proposal which is not part of actual language standard yet, so, just like for JSX, you need to use custom plugin to support it (I think it's acorn-class-fields from that list).

kariae commented 6 years ago

Ah, you're right, thanks for the clarification, that's said I think the plugin that will help in this case is acorn-static-class-property-initializer but it only supports static methods for now, so I think I need to find how all this works :D