acornjs / acorn-jsx

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

Proposal: throw syntax error for `}` and `>` in JSX text. #106

Closed bradzacher closed 4 years ago

bradzacher commented 4 years ago

Feature Request

The JSX spec [1][2] lists } and > as invalid JSX text characters.

JSXTextCharacter :

  • SourceCharacter but not one of {, <, > or }

However, acorn does not throw a syntax error when it encounters a naked } or > in a JSXText string.

According to the spec, the only way you should be able to include either of these characters (similarly for { and <), is via a string expression: {'>'}.

Describe the solution you'd like I propose that acorn should follow the JSX spec, and throw a syntax error if it encounters a "naked" } or > within jsx text.

From my experience, it's uncommon that these characters are intentionally put in JSX text, and are instead the result of typos (i.e. typing {}, but having an editor auto-complete an extra } => {}}), or copy pasting errors.

Flow has already updated their parser to flag this as an error [3][4]. I have submitted issues for this in both TypeScript [5] and Babel [6].

Teachability, Documentation, Adoption, Migration Strategy

I think the best way to document this would be via clear and explicit error messaging. For example, the following code:

function F() {
  return <div>></div>;
}

function G() {
  return <div>{1}}</div>;
}

produces the following flow errors:

4:   return <div>></div>;
                 ^ Unexpected token `>`. Did you mean `{'>'}`?
8:   return <div>{1}}</div>;
                    ^ Unexpected token `}`. Did you mean `{'}'}`?

flow.org repl


Related: [1] https://facebook.github.io/jsx/ [2] https://github.com/facebook/jsx/pull/18 [3] https://github.com/facebook/flow/blob/master/Changelog.md#01160 [4] facebook/flow@e1d0038 [5] https://github.com/microsoft/TypeScript/issues/36341 [6] https://github.com/babel/babel/issues/11042