Create a React app using Webpack 5
Tags: webdev, javascript, react, webpack
Published: 2023-10-30 18:08:15

### React

**React** is a Javascript library for building user interfaces. It is a declarative library, meaning you can describe what you want UI to look like, and React takes care of the rest.

React: [React Learn](https://react.dev/learn)

**Webpack** and **Babel** are used for React application because Webpack bundles and manage dependencies individually like JavaScript, CSS and assets and loads to the browser and Babel is used to transpile modern JavaScript applications into code that can run in all environments for React components.

### Webpack

**Webpack** is a static module bundler for modern JavaScript applications. It creates _dependency graphs_ from one or more entries and combines modules your project needs into one or more bundles, which are static assets to create content form.

Refer: [Webpack Documentation](https://webpack.js.org/concepts/)

### Babel

**Babel** is a JavaScript compiler or transpiler mainly used to convert ECMAScript2015+ to compatible versions of JavaScript in browsers.

Refer: [Babel Documentation](https://babeljs.io/docs/)

### Initial Step

#### Create a workspace or folder to create a project

```sh
mkdir project-for-react-using-webpack
cd project-for-react-using-webpack
```

#### Initialize with npm

Initializing with npm will create a `package.json` file to keep track of dependencies and metadata.

```sh
npm init -y
```

#### Add react and react-dom
```sh
npm install react react-dom
```

_React_ provides tools to create a view of components or parts of the page.

_ReactDOM_ provides DOM-specific methods that can be used at the top level for an efficient way of managing DOM elements.


#### Install webpack packages as devDependencies

```sh
npm install --save-dev webpack webpack-cli webpack-dev-server
```

_Webpack_ is used to bundle the modules in the application.

_Webpack CLI_ provides a flexible set of commands for developers to increase speed when setting up a custom webpack project.

_Webpack Dev Server_ is a tool for starting a static server for your assets.

#### Install Babel related packages as devDependencies

```sh
npm install --save-dev  @babel/core babel-loader @babel/preset-react  @babel/preset-env
```

_Babel Core_ The core module that wraps everything in our transform API, Transform syntax: Polyfill features that are missing in your target environment.

_Babel Loader_ exposes a utility for building loaders that allows users to customize Babel's configuration for each processed file.

_Babel Preset React_ allows you to write React components using JSX and other modern JavaScript features while still being able to run your code in older browsers or other environments that may not support these features out of the box.

_Babel Preset Env_ allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s).

#### Install html-webpack-plugin package
```
npm install --save-dev html-webpack-plugin
```
- _HTML Webpack Plugin_ is added to simplify the creation of HTML files to serve your webpack bundles.

#### Configure webpack by adding required files

* Create a directory `src`, add a file with the name `index.js` and add the below code in it.

``` js
import React from 'react';
import App from './App';
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
  <React.StrictMode>
      <App/>
  </React.StrictMode>,
);
```
> No need to worry about the above code and what it does.

* Add `App.js` with below code
``` js
import React from 'react';

const App = () => <div>App</div>;

export default App;
```

* Create a file of `index.html` inside the folder `src`
``` html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
```

* Create a webpack configuration file name as `webpack.config.js`.

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

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.resolve(__dirname, "dist"),
  },
  resolve: {
    extensions: ['js', 'jsx', 'ts'],
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/Components'),
      '@config': path.resolve(__dirname, 'src/Config'),
      '@page': path.resolve(__dirname, 'src/Pages'),
      '@routes': path.resolve(__dirname, 'src/Routes'),
      '@services': path.resolve(__dirname, 'src/Services'),
      '@utils': path.resolve(__dirname, 'src/Utils'),
    },
  },
  module: {
    rules: [
        {
            test: /\.svg$/,
            use: ['@svgr/webpack'],
        },
        {
            test: /\.(png|jp(e*)g|svg|gif)$/,
            use: ['file-loader'],
        },
        {
            test: /\.css$/i,
            use: ["style-loader", "css-loader"],
        },
      {
        test: /\.?(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "src", "index.html"),
    }),
  ],
}
```

_entry_: An entry point indicates which module webpack should use to begin building out its internal dependency graph.

_output_: The output property tells webpack where to emit the bundles it creates and how to name these files.

_resolve_: A resolver is a library which helps in locating a module by its absolute path.

_module_: Allows you to preprocess files as they are loaded and since everything is a module in Webpack.

_plugins_: Plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables.

* Replace scripts in `package.json`
Replace the below snippet in `package.json` with scripts
``` js
"scripts": {
  "start": "webpack-dev-server --mode development",
  "build": "webpack --mode production",
},
```

### Build modules and start the dev server
``` sh
npm run build
```

Running the above command in the command prompt will create build modules in the output path provided in the webpack config

#### Note: Regarding `Create React App`😁

This Create React App wraps all the required dependencies like Babel and Webpack for the React project itself so that you can focus on coding the React app only.

Github Link: [React Boilerplate](https://github.com/iredith/react-boilerplate)

<center>**** 💻ALL THE BEST💻 ****</center>