Why is browser.min.js needed in reactjs?

后端 未结 3 1341
佛祖请我去吃肉
佛祖请我去吃肉 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:30

    Found that Babel's own 'browser.js' isn't working anymore?

    'browser.js' was deprecated back in 2015, meaning that continuing to be able to compile in-browser JSX became a little bit tougher.

    Thankfully, the babel-standalone project is a drop-in replacement, and appears to be in active development.

    'babel-standalone' seems to be endorsed by the BabelJS project itself, noted by its inclusion on this page.

    0 讨论(0)
  • 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:

    <div id="example"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
      );
    </script>
    

    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.

    0 讨论(0)
  • 2021-01-02 04:41

    You've written the code in Babel (ES7) and not in a version of JavaScript that the browser can handle natively, and you are delivering the ES7 to the browser instead of transpiling it at build time.

    0 讨论(0)
提交回复
热议问题