React is a javascript library that is created and maintained by Facebook. It is known for its speed and efficiency in loading and rendering an application. In this article, we will be creating our own React project, render it in our browser using babel, bundle it, and run it on our local server, using webpack tools.

Prerequisites:

-Latest version of node. You can install it from here.

Creating a simple React project

Let us now create a sample project with the following folder structure.

 webpack-demo-app
+ |- public
+   |- index.html
+   |- app.js
+ |- /src
+   |-components
+     |-Header.js
+   |- app.js

Now, let us initialize our project using npm so that we can install different third party modules and use them in our project. To do that, run the below command in the terminal.

npm init

You can fill in the responses for each field asked, or you can press enter on each question which fills in the default response.

On initialization of our project a new file named package.json will be added to our project directory which basically keeps track of the packages installed, project dependencies etc. and our project's folder structure might look like this.

 webpack-demo-app
  |- public
    |- index.html
    |- app.js
  |- /src
    |-components
      |-Header.js
    |- app.js
+ |package.json

Cool, now we are good to install any node modules, libraries to our project. Let us now install React and ReactDOM which are the two packages that we need to install in order to start writing react code. For that, we need to run the following npm command in the terminal.

npm install react@16.13.1 react-dom@16.13.1

Let us now quickly setup some sample code in our index.html file of our public directory and create a root div to render our React component, and refer the javascript file app.js, which is in the same folder.

Here you need to note a point that, we do not make any changes to the app.js file inside the public folder. We will be using Webpack which writes code into it, which will be discussed later in the article. On completion, the code might look like this.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    <script src="./app.js"></script>
</body>
</html>
index.html

Now, let us create a simple component in our Header.js file, inside the components folder that writes 'Hello World' to the screen. On completion, the code might look like this.

import React from 'react'

const Header = () => {
    return (
        <div>
        <h1>Hello World!</h1>
        </div>
    )
}

export default Header
Header.js

Now, in the app.js file of the src folder, let us render our component to the root div that we have created in our index.html file. On completion, the code might look like this.

import ReactDOM from 'react-dom'
import React from 'react'
import Header from './components/Header'

ReactDOM.render(<Header />, document.getElementById('root'))
app.js

Cool, now we have our simple react app that renders 'Hello World' to the screen.

Configuring Webpack to our project

Generally, we write our javascript into a file and refer it to our htm file using the script tag, consider a project having many number of javascript files, refering each file in a script tag would be a tedious task.

To make that tedious task simple, we use webpack. Webpack bundles all our javascript files in a sensible order so that we can refer a single javascript file that contains all the code, into our index.html file, which gets our job done.

Webpack can be used not only for bundling javascript files, but also css, png, jpg, sass files together into a single, short-file. Here, in this article, we are going to learn how to bundle multiple javascript files into one using webpack and some of its tools.

Let us now quickly jump in to writing the code for that. Starting off, we need to install webpack and webpack-cli into our project. The npm command for the same is given below.

npm install webpack@4.43.0 webpack-cli@3.3.11

Now, we have to configure webpack to our project with some properties. To do that, we need to create a file named 'webpack.config.js'. Let us quickly create the file and populate it with some code. To do that, we need to know about webpack properties.

Webpack properties

For webpack, to understand the way of bundling a project, it needs a few configurations which we provide in the form of properties, in the webpack.config.js file. Below are a few properties, that you need to know about.

entry: This specifies the entry point of the project, to webpack so that it can start bundling the files. For our project the entry point is the app.js file in our src folder.

output: This is the object that specifies the output file into which the bundled code is written. The object needs to have two properties, 'path', that specifies the absolute path to the output file, 'filename', that specifies the filename of the output file.

mode (optional): This specifies the mode of bundling, it can be 'development' or 'production'. Setting the mode to production reduces the size of the output file.

Now, we have set the bare minimum properties needed to bundle our application using webpack. Our webpack.config.js now might look like this.

const path = require('path')

module.exports = {
    mode: 'development',
    entry: './src/app.js',
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'app.js'
    }
}
webpack.config.js

Configuring Babel

As we are using JSX and some other ES6 syntax in our react project, most of the browser would not understand them. In order to make our react code work in all the browsers, we need to compile them to ES2015, which is understood by all the browsers.

To do that, we need to use a compiler that does the job for us. Babel is a compler that converts ES2015+ scripts backward to ES2015 so that any browser can understand it. Now, let us quickly install babel, and a babel-loader for webpack along with some babel-presets, by running the below command in the terminal. You can find more information about webpack loaders here.

npm install babel-core@6.26.3 babel-cli@6.26.0 babel-loader@7.1.1 babel-preset-env@1.7.0 babel-preset-react@6.24.1

The above command installs babel along with the required presets to convert our ract code to ES2015 code.

Now, let us configure babel to our webpack in the webpack.config.js file. We need to assign a rule in order convert all the javascript file contents using babel. For that we create a property named module, this property is an object that contains the rules array which is again a set of objects. Every object inside the rules array is considered as a rule.

Inside the rules array, now lets write a rule for babel. We have to write three properties inside the object, 'test', a regular expression that specifies to what files the rule must be applied, we need the filenames that end with .js extension, 'loader', what is the loader to be used, we use the babael-loader which we recently installed, 'exclude', what are the files, folders to exclude from the rule, we exclude the files in our node_modules folder. On completion, the webpack.config.js file might look like this.

const path = require('path')

module.exports = {
    mode: 'development',
    entry: './src/app.js',
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'app.js'
    },
    module:{
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    }
}
webpack.config.js

Next, we need to create a file named .babelrc which is like a configuration file for babel, that contains the properties such as presets that are needed to be used. We have to add the env and the react presets that we recently installed, to the presets array in the .babelrc file, on completion it might look like this.

{
    "presets": [
        "env",
        "react"
    ]
}
.babelrc

Now our react app is ready. To test, save all the files, create a script in the package.json file that runs the command 'webpack'. On adding that, the package.json file might look like this.

{
  "name": "webpack-demo-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.1",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11"
  }
}
package.json

Now run the below command in your terminal. This command will bundle your app using webpack.

npm run build

Now, go to the physical directory and open the index.html file, you will see 'Hello World!' appearing on the screen.

But, this is not what we really want, we want a local server to host our application. For that, we need to install a tool called 'webpack-dev-server'. We can do that by executing the below command in the terminal.

npm install webpack-dev-server@3.10.3

Now, as we have installed the webpack-dev-server we need to configure it in our webpack.config.js file. We will need to add a property named 'devServer' which is an object.

The object contains the properties 'contentBase', that refers to the folder of the index.html file that needs to be hosted, 'port' which is the port number on which the app must be hosted. On completion, the webpack.config.js file might look like this.

const path = require('path')

module.exports = {
    mode: 'development',
    entry: './src/app.js',
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'app.js'
    },
    module:{
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        port: 9000
    }
}
webpack.config.js

Now, add a script to run the webpack-dev-server, like we have added to bundle our files. On adding, your package.json file might look like this.

{
  "name": "webpack-demo-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "serve": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.1",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  }
}
package.json

Finally, run the below command to run our application on the local server.

npm run serve

Go to http://localhost:9000/ to see the app running.

Thank you for reading. Hope you found this article useful.

To learn more about webpack, you can read articles here and here.