Search code examples
reactjswebpackwebpack-dev-serverwebpack-2

Why we need to use web-pack in ReactJs?


Why do we need to use webpack, is it only for bundling and inheriting Plugins to minimize and compress. what are all the major roles webpack plays in web application development?


Solution

  • The uses of webpack include

    • Transpile the JSX syntax (HTML tags inside Javascript) into JS
    • Transpile the ES6 syntax (arrow functions, spead operator, etc) into browser supported versions of Javascript.
    • It is much better to split code into separate files (modules) which can be imported. Webpack 'bundles' all those files into a single JS file for production use
    • At the time of bundling, it can also perform optimisations like minify, uglify, etc.

    BTW, you don't need to use webpack. For example,

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>My First React Example</title>
      </head>
      <body>
        <div id="greeting-div"></div>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/cjs/react.development.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/cjs/react-dom-server.browser.development.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
        <script type="text/babel">
          var Greeting = React.createClass({
            render: function() {
              return (
                <p>Hello, Universe</p>
              )
            }
          });
    
          ReactDOM.render(
            <Greeting/>,
            document.getElementById('greeting-div')
          );
        </script>
      </body>
    </html>
    

    Here, the JSX code is getting 'transpiled' to JS on-the-fly. However, this is not very efficient in production use.