Skip to content

Commit

Permalink
add a friendly error message for jsx in js
Browse files Browse the repository at this point in the history
  • Loading branch information
evanw committed Nov 30, 2021
1 parent 9ec5c57 commit 63cca7f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
3 changes: 2 additions & 1 deletion internal/bundler/bundler_default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,8 @@ func TestJSXSyntaxInJS(t *testing.T) {
Mode: config.ModeBundle,
AbsOutputFile: "/out.js",
},
expectedScanLog: `entry.js: ERROR: Unexpected "<"
expectedScanLog: `entry.js: ERROR: The JSX syntax extension is not currently enabled
NOTE: The esbuild loader for this file is currently set to "js" but it must be set to "jsx" to be able to parse JSX syntax. You can use 'Loader: map[string]api.Loader{".js": api.LoaderJSX}' to do that.
`,
})
}
Expand Down
16 changes: 16 additions & 0 deletions internal/js_parser/js_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -3473,6 +3473,22 @@ func (p *parser) parsePrefix(level js_ast.L, errors *deferredErrors, flags exprF
return p.parseParenExpr(loc, level, parenExprOpts{forceArrowFn: true})
}

// Print a friendly error message when parsing JSX as JavaScript
if !p.options.jsx.Parse && !p.options.ts.Parse {
var how string
switch logger.API {
case logger.CLIAPI:
how = " You can use \"--loader:.js=jsx\" to do that."
case logger.JSAPI:
how = " You can use \"loader: { '.js': 'jsx' }\" to do that."
case logger.GoAPI:
how = " You can use 'Loader: map[string]api.Loader{\".js\": api.LoaderJSX}' to do that."
}
p.log.AddWithNotes(logger.Error, &p.tracker, p.lexer.Range(), "The JSX syntax extension is not currently enabled", []logger.MsgData{{
Text: "The esbuild loader for this file is currently set to \"js\" but it must be set to \"jsx\" to be able to parse JSX syntax." + how}})
p.options.jsx.Parse = true
}

if p.options.jsx.Parse {
// Use NextInsideJSXElement() instead of Next() so we parse "<<" as "<"
p.lexer.NextInsideJSXElement()
Expand Down
4 changes: 3 additions & 1 deletion internal/js_parser/js_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4153,7 +4153,9 @@ func TestNewTarget(t *testing.T) {
}

func TestJSX(t *testing.T) {
expectParseError(t, "<a/>", "<stdin>: ERROR: Unexpected \"<\"\n")
expectParseError(t, "<a/>", "<stdin>: ERROR: The JSX syntax extension is not currently enabled\n"+
"NOTE: The esbuild loader for this file is currently set to \"js\" but it must be set to \"jsx\" to be able to parse JSX syntax. "+
"You can use 'Loader: map[string]api.Loader{\".js\": api.LoaderJSX}' to do that.\n")

expectPrintedJSX(t, "<a/>", "/* @__PURE__ */ React.createElement(\"a\", null);\n")
expectPrintedJSX(t, "<a></a>", "/* @__PURE__ */ React.createElement(\"a\", null);\n")
Expand Down

0 comments on commit 63cca7f

Please sign in to comment.