Why is browser.min.js needed in reactjs?

后端 未结 3 1340
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 03:44

I’m trying to build a simple React application and am wondering why I need the browser.min.js file.

I have included both react and react-dom.js, but nothing is displ

3条回答
  •  清酒与你
    2021-01-02 04:41

    As you can see in your snippet, the script tag is of type "text/babel", and that's because you are coding using JSX (Javascript with XML on it) inside it.

    JSX is coding sugar created to make it more "intuitive" to build XML (HTML in this case) components in javascript code (not only React elements, though). React makes use of it as an abstraction layer over the composition methods used to create/define UI elements. But JSX is not a globally accepted standard, so it isn't supported by all browsers. This is the reason that you need a third party "compiler" library to transform the JSX to vanilla JS, and this is where BABEL comes through.

    BABEL is a javascript compiler, and importing its "browser.min.js" file, you are enabling it to "compile" the code inside "text/babel" script tags and execute it as vanilla javascript.

    So, in your example, you have the next code:

    And "browser.min.js" will process it when the page has loaded and the javascript code that will be executed should be something like this:

    ReactDOM.render(
      React.createElement('H1', null, 'Hello world!'), 
      document.getElementById('example'));
    

    The main alternatives you have if you don't want to load this "browser.min.js" are:

    1. Have your React code in separate files and compile them whenever you make a change (all of this is server-side). Your html code should reference the compiled files (which should have only vanilla JS code) instead of your original JSX ones. There are several ways to do this depending on your coding tools.

    2. Use only vanilla JS to create and define your React "Html" hierarchy (React.createElement(...)).

    Explaining in more detail these methods should be covered in other questions.

提交回复
热议问题