Create a React App with Webpack (React 18)

Create a React App with Webpack (React 18)

Table of contents

No heading

No headings in the article.

Hi Everyone! today we are going to create a react app with Webpack configuration. Creating react app with Webpack gives us complete control over the entire app. This method of creating react app also helps in building a micro front-end which we will discuss in my next blog.

To start creating the project, let's create a folder we can call it ReactWebpack. Inside the ReactWebpack folder create another folder with the name "src". Inside the src folder create two files index.html and index.js. Since React app is a single-page application our entry point will be the index.js file in the webpack configuration. (Note: You can add another folder inside the src folder and name it Public and move the index.html file into that folder. But that is not compulsory)

After this process, your folder structure should look like this.

Now it's time to initialize the project. For initializing the project do type the following command in the terminal.

After that, you will get the following option, type the name without any space and then press enter repeatedly.

After that, you will notice that package.json file has been created in your project.

Now, it's time to add a list of packages. First, we will download packages that we will require both in the production and development environment. Type the following command.

Now we will add some packages as dev dependencies. Add the following packages. For your ease of installing the packages, I have kept the following as plain text so that you can copy and paste it into the terminal. ( Note: I am adding support for sass as well but you can ignore those packages)

npm i @babel/core @babel/preset-env @babel/preset-react babel-loader --save-dev css-loader html-webpack-plugin postcss-loader postcss-preset-env sass sass-loader style-loader webpack webpack-cli webpack-dev-server

or

yarn add -D @babel/core @babel/preset-env @babel/preset-react babel-loader --save-dev css-loader html-webpack-plugin postcss-loader postcss-preset-env sass sass-loader style-loader webpack webpack-cli webpack-dev-server

Have you followed all the steps, which I have told in the above paragraphs?? Great!! Now, we can completely focus on writing the code on our code editor and make this react project up and running with webpack.

First, go to index.html and add the boilerplate of HTML 5 and add a div tag with id as root. This div will be the point through which index.js will be connected. After you add the HTML boilerplate with the div tag it should look something like this:

Now, we need to add scripts tag in the package.json file to use the webpack configuration we will be adding the following code.

You might think what is this webpack.config.js in the scripts? Don't worry we will be creating a file with this name now. But before that let's finish the react code setup. Let's add App.js inside the src folder and add a functional component with a plain HTML h1 tag with the name Hello World. Please refer to the following code.

Your App.js file code should look like the above. Now, let's move to the index.js file and add the following code to connect the index.js file with the index.html file, as in react, no matter how many components we create it ultimately adds up and gets injected into the single index.html file which we create. That's the beauty of a single-page application. As we are using react 18 write the following code in the index.js file.

Although we have written a few lines of code this is still far from being ready to be used as react project. Now guess what we need to do?

That's right now we will add webpack configuration so that it can understand jsx and js components. I will take you through each step line by line so that you get an understanding of the flow.

Let's create the file webpack.config.js.The file should be created outside the src folder. The file structure should look like this.

Now inside the webpack.config.js we need to add configurations that would help the webpack to start the react project. First, we need to add the entry point and the output. Write the following code.

Explanation: We will be using nodejs in-built package path for adding a new folder with the name dist when the build will be created. For now, we have defined our entry point as index.js (Make sure the path of the entry point is correct) and as output, we will create a new folder dist inside which our optimized code will be added automatically after we run the build script.

Type yarn build in the terminal. You will get some errors but you will see a dist folder will be created. Inside the dist folder, main.bundle.js file will be created automatically. Inside the dist folder, we will always have an optimized build that can be used to run the project.

After this basic set up we need to add configurations for js, jsx, CSS, SCSS files. We will add configurations for js and jsx files with the help of babel-loader. Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards-compatible version of JavaScript in current and older browsers or environments. In order to do that add the following code.

Explanation: After the output object, we need to add another object module. Inside the module object, we add rules which is an array of objects. In this rules array, we can add configurations for different file types with the help of loaders which we will be using in the project. In the above code, we have added configuration for js/jsx file. We have also added a plugin html-webpack-plugin in the plugins object which helps in creating an optimized HTML file in the dist folder after we build it.

After this, inside the rules array we will add configurations for CSS, SASS/SCSS and Image files. Add the following code inside the rules array

 module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: path.resolve(__dirname, "src"),
        exclude: /node_modules/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env", "@babel/preset-react"],
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.s[ac]ss$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.(jpg|png|jpeg|gif)$/,
        type: "asset/resource",
      },
    ],
  },

We have added all the necessary code so far with the loaders that are needed, now we need to add a dev server and a small in-built optimization code in the project. The dev server will help us in starting the react project like create-react-app and we won't have to create the build again and again while we work in a development environment. The final code will look like this.

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const port = process.env.PORT || 3000;

module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: path.resolve(__dirname, "src"),
        exclude: /node_modules/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env", "@babel/preset-react"],
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.s[ac]ss$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.(jpg|png|jpeg|gif)$/,
        type: "asset/resource",
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      filename: "index.html",
    }),
  ],
  devServer: {
    static: {
      directory: path.resolve(__dirname, "dist"),
    },
    port: port,
    historyApiFallback: true,
    open: true,
  },
  optimization: {
    splitChunks: {
      chunks: "all",
    },
  },
};

Explanation: We have added a dev-server which will have an assigned port. I have configured the port at the top of this code to 3000 for the dev environment and the optimization object which we have added at the bottom is in-built which creates multiple chunks to optimize the build.

Now if you run the following code in the terminal, you will see that the build becomes successful.

npm run build
or 
yarn build

Now, as we also configured the dev-server, now you can also try in the terminal.

yarn dev
or 
npm run dev

You will see that development server starts in the browser and you can try editing the heading in the app.js file. You will see that you will be able see the changes on the go just like create-react-app.

Summary

  1. Create a project folder.

  2. Inside the folder add an src folder

  3. Inside the src folder add index.js, app.js, index.html files

  4. Initialize the project with npm init or yarn init (Based on your package manager choice).

  5. Install the packages listed above.

  6. Add code on the index.html

  7. Add code on App.js file

  8. Add react entry point code inside the Index.js file

  9. Add scripts tag in the package.json file.

  10. Create webpack.config.js file and add configurations for supporting all types of files to be used in the project.

I had fun writing this blog. But if you have any queries, suggestions, or doubts, please reach out to me on my twitter handle @rahul_dofficial. Thank you so much for your time. Until next time happy coding.