Home  Reactjs   How bundlin ...

How bundling works in reactjs

Bundling in React (and in general web development) refers to the process of combining multiple JavaScript files (and other assets like CSS and images) into a single file (or a few files). This is typically done using a bundler tool like Webpack, Parcel, or Rollup. Bundling helps to reduce the number of HTTP requests needed to load a web application, which can improve the performance and load time of the application.

How Bundling Works in React

Bundling involves several steps:

  1. Entry Point: The bundler starts from one or more entry points, which are the main files of the application (e.g., index.js).
  2. Dependency Graph: The bundler analyzes the dependencies of each module starting from the entry point and builds a dependency graph.
  3. Transformation: The bundler transforms the code (e.g., by transpiling modern JavaScript to older syntax for compatibility) and combines the modules.
  4. Output: The bundler outputs the bundled files, which can be a single file or multiple files (chunks).

Example of Bundling in React with Webpack

Step 1: Setup the Project

  1. Create a new React app without Create React App:

    mkdir bundling-example
    cd bundling-example
    npm init -y
    
  2. Install React and ReactDOM:

    npm install react react-dom
    
  3. Install Webpack and Babel:

    npm install webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env @babel/preset-react html-webpack-plugin
    

Step 2: Project Structure

Create the following project structure:

bundling-example
│
├── public
│   └── index.html
│
├── src
│   ├── components
│   │   └── App.js
│   └── index.js
│
├── .babelrc
├── package.json
└── webpack.config.js

Step 3: Create React Components

src/components/App.js:

import React from 'react';

const App = () => {
  return <h1>Hello, React!</h1>;
};

export default App;

src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

ReactDOM.render(<App />, document.getElementById('root'));

Step 4: Create HTML File

public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React Bundling Example</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

Step 5: Configure Babel

.babelrc:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

Step 6: Configure Webpack

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
    }),
  ],
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 9000,
  },
};

Step 7: Update Scripts in package.json

Add the following scripts to package.json:

"scripts": {
  "start": "webpack serve --mode development",
  "build": "webpack --mode production"
}

Step 8: Run the Application

  1. Start the development server:

    npm start
    
  2. Build the production bundle:

    npm run build
    

Explanation

  1. Entry Point: Webpack starts bundling from src/index.js.
  2. Dependency Graph: Webpack analyzes the imports and builds a graph of dependencies.
  3. Transformation: Webpack uses Babel to transform JSX and modern JavaScript into browser-compatible code.
  4. Output: Webpack outputs the bundled code into dist/bundle.js.
  5. HTML Webpack Plugin: This plugin injects the bundled JavaScript file into public/index.html and outputs it to dist/index.html.
  6. Webpack Dev Server: Serves the application in development mode with hot-reloading.

Bundling ensures that all the dependencies and modules are combined into a single file (or a few files), which simplifies the deployment and improves the performance of the application.

Published on: Jul 31, 2024, 01:35 AM  
 

Comments

Add your comment