Why ReactJS needs compilation

Viewed 4844

Reactjs is consists of .js files and JavaScript doesn't compile as it's an interpreted language. Then why Reactjs need to be compiled? I read that it uses the JSX compiler.

3 Answers

JSX includes markup syntax that isn't valid javascript. The JSX "compiler" translates the markup into vanilla javascript. You can see this yourself using the babel repl:

JSX in:

const Test = () => <div>test</div>

Javascript out:

"use strict";

var Test = function Test() {
  return /*#__PURE__*/React.createElement("div", null, "test");
};

There's also the matter of bundling, resolving imports, adding polyfills, etc.

It goes through a sort of minimization, and converts all that non-stock-javascript JSX code into regular Javascript. It's not making it any faster really, like compiling C to machine code, but it's converting it into Javascript that your browser can understand.

You don't need to compile javascript to use react. Check out the documentation for how to use it without.

However, there are certain components in declarative GUI systems like react that are verbose and cumbersome to write in a generic language. Thus, react provides a Javascript variant known as "JSX" that allows you to write XHTML right inside the javascript code. A browser does not know JSX since it was invented by the react team. Thus, react needs a way to transform the parts of fancy XML into generic Javacript your browser can understand.

Related