Search code examples
javascriptreactjscompilationbabeljsjsx

How is the JSX-compilation triggered?


I'm currently studying React and have set up a simple "Hello, world"-example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

      ReactDOM.render( 
        <h1>Hello, world!</h1>,
        document.getElementById('root')
      );

    </script>
  </body>
</html>

BTW. I deliberately did not use a toolchain like create-react-app in order to understand the basics.

The following code snippet is actually something, that a web browser does not understand, because it's not standard JavaScript.

ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById('root'));

It is JSX (JavaScript Syntax Extension), so it needs to be compiled. For example with Babel. I know that I included in the head of the html-file the Babel-compiler. But to me it is unclear when and how the actual compilation process takes place.

Is there a callback in the Babel-package that is called before the actual rendering and compiles the file in which it was via the <script src="">-tag included?


Solution

  • The Babel script performs the following:

    1. Adds a DOMContentLoaded listener
    2. Loads all the scripts if the scripts have a src
    3. Transforms the code and injects a <script> to evaluate the newly-transformed code.