What is JSX, why does React use JSX, how does babel translate JSX

What is JSX, why does React use JSX, how does babel translate JSX

In the front-end framework, there are two schemes for "describing the UI", one is the JSX syntax, and the other is the template language.

Among them, React is the chosen JSX, and Vue is the chosen template language.

JSX is actually a syntactic sugar. When writing React code, you can write without using JSX. In React, the JSX code you write will eventually be compiled by babel.

// JSX语法
const element = <h1>Hello,World!</h1>
// babel编译后
var element = React.createElement("h1",null,"Hello,world!");//React17版本之前
// React17版本之后
var _jsxRuntime = require("react/jsx-runtime");
var element = _jsxRuntime.jsx("h1",{children:"Hello World!"});

JSX is converted by babel into the form of React.createElement or _jsxRuntime.jsx. After the function is executed, the virtual DOM is returned, so you can directly write the form of React.createElement or _jsxRuntime.jsx without using JSX.
So the code we write will eventually be built into a virtual DOM tree. JSX is a kind of syntactic sugar of XML-like syntax, which makes it more convenient for developers to build this virtual DOM tree and makes the code more concise.

So how does babel convert the JSX syntax into the form of React.createElement or _jsxRuntime.jsx?

The process of babel compiling JSX is divided into three parts:

  1. parse: Convert JSX code to AST through parse.
  2. transform: The plug-in is used in the transform stage @babel/plugin-transform-react-jsx. Its core is the visitor function. Through this function, the AST is traversed, and different processing is performed according to different node types, and the AST corresponding to the createElement corresponding to JSX is generated.
  3. generate: Finally, generate converts AST to JS.

Guess you like

Origin blog.csdn.net/qq_51965698/article/details/129251204
JSX