DEV Community

Cover image for Create a React app using Webpack 5
ajay-8192
ajay-8192

Posted on

Create a React app using Webpack 5

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

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

Babel

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

Refer: Babel Documentation

Initial Step

Create a workspace or folder to create a project

mkdir project-for-react-using-webpack
cd project-for-react-using-webpack
Enter fullscreen mode Exit fullscreen mode

Initialize with npm

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

npm init -y
Enter fullscreen mode Exit fullscreen mode

Add react and react-dom

npm install react react-dom
Enter fullscreen mode Exit fullscreen mode

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

npm install --save-dev webpack webpack-cli webpack-dev-server
Enter fullscreen mode Exit fullscreen mode

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

npm install --save-dev  @babel/core babel-loader @babel/preset-react  @babel/preset-env
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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.
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>,
);
Enter fullscreen mode Exit fullscreen mode

No need to worry about the above code and what it does.

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode
  • Create a file of index.html inside the folder src
<!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>
Enter fullscreen mode Exit fullscreen mode
  • Create a webpack configuration file name as webpack.config.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"),
    }),
  ],
}
Enter fullscreen mode Exit fullscreen mode

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
"scripts": {
  "start": "webpack-dev-server --mode development",
  "build": "webpack --mode production",
},
Enter fullscreen mode Exit fullscreen mode

Build modules and start the dev server

npm run build
Enter fullscreen mode Exit fullscreen mode

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

**** ๐Ÿ’ปALL THE BEST๐Ÿ’ป ****

Top comments (2)

Collapse
 
webdiscus profile image
webdiscus

alternatively, instead of html-webpack-plugin can be used the modern powerful html-bundler-webpack-plugin.

This plugin is much easier to use than the HTML Webpack Plugin.
Using the new HTML Bundler Plugin, the HTML file is the entry point for all asset source files.

Collapse
 
ajay-8192 profile image
ajay-8192 • Edited

@webdiscus Thanks for the suggestion ๐Ÿ™๐Ÿผ, I will go through provided the alternate HTML bundler plugin.