React setup with webpack for beginners
Tags: webdev, react, webpack, javascript
Published: 2021-04-26 04:36:50

There are many ways to set up a react project and the popular ones you may hear of create-react-app and webpack. So today we'll see how to set up a react project with webpack and babel in a simple way.

## So what is Webpack?

The definition says Webpack is a static module bundler for modern JavaScript applications and what do we mean by that?

Webpack is a bundler that bundles all the javascript files and internally it makes a dependencies graph that is responsible for mapping all your modules and depending on this graph it creates a bundle.js file that can be plugged into your HTML file. 

So in this article, I want to show you how to set up your first react app with webpack and this will be a very minimal setup and afterward, you'll be able to extend the features depending on your needs.

## 1.Initial Phase (Folder Setup)

First, we'll start by creating a Project folder and then a *public* and *src* folder inside it. Public folder will be used to serve the application and this folder will be everything to publish your application. In the src folder, all the javascript files will be there and this folder will be bundled into a single javascript file and will be placed automatically in the public folder.

```
mkdir webpack-react
cd webpack-react
mkdir public src 
```
Next, we'll create an index.html file inside the public folder with the following content.

```
cd public
touch index.html
```

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React with webpack</title>
</head>
<body>
    <div>
        <h1>Hello Webpack</h1>
    </div>
    <script src="./bundle.js"></script>
</body>
</html>
```

## 2. Setting up Webpack

Now before we start installing webpack and other npm packages we need to set up package.json first. Setting up package.json is easy either you can do it manually by running `npm init` by this you can fill in all the details by yourself or you can let npm handle it by simply adding -y at the end like `npm init -y`. This will create the package.json in the root folder.
Let's install some packages first and I'll explain each one by one.

```
npm i webpack webpack-cli webpack-dev-server --save-dev
```

* We need `webpack` to bundle all our javascript code to single and to build our application.
* `webpack-dev-server` is needed to serve the application in the local web server for development purposes.
* `webpack-cli` provides a flexible set of commands for developers to increase speed when setting up a custom webpack project.

*(Note: Add a .gitignore file to avoid node_modules to push in git)*

Let's add a `start` script now in *package.json* to run `web-dev-server`

```json
...
    "start": "webpack serve --mode development"
...
```

You can run `npm start` on your command line to start the application on your local server. Now let's generate *bundle.js* and see how we can bundle all the javascript code into a single file. Now we need to add a webpack configuration so now we will add *webpack.config.js* in the root folder. 

```
touch webpack.config.js
```

and update the `start` script in *package.json*.

```json
...
start: "webpack serve --config ./webpack.config.js --mode development",
...
```

Next, let's create an index.js file inside src where all the javascript code will be linked. 

```
cd src
touch index.js
```

and add a simple log inside it

```javascript
console.log("Hello World")
```

Now will add an entry point inside the webpack configuration to bundle in our case it is *src/index.js* and if *index.js* imports another javascript file it bundles them too.
The next step is to add an output file which will be *bundle.js* and this file is linked to the *public/index.html* and third step is to add a folder that will be used by the webpack dev server to serve our application to the browser. The content will look like this.

``` javascript 
const path = require('path');
 
module.exports = {
  entry: path.resolve(__dirname, './src/index.js'),
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
  },
};
```
*(Note: path is used to resolve them properly across the operation system)*

Now run `npm start` in your command line you'll see Hello World logged in your browser console.

Now we will add Babel to transpile back the modern javascript features (ES6 and others) to vanilla javascript. Let's install some packages for babel.

```
npm i @babel/core @babel/preset-env babel-loader --save-dev
```
* `@babel/preset-env` is a smart preset that 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).
* Loaders tell webpack how to interpret and translate files. The transformation happens on a per-file basis before adding to the dependency graph.

We need to add the babel in the build process in *webpack.config.js*. Your *webpack.config.js* will look like this.

```javascript
const path = require('path');
 
module.exports = {
  entry: path.resolve(__dirname, './src/index.js'),
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js']
  },
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
  },
};
```
*(Note: module is added in which we have rules which will test all the .js file and exclude node_modules and will be using babel-loader for it)*

Now let's add a babel configuration for that let's create a *.babelrc* file in the root folder and add the below configuration inside.

```
touch .babelrc
```
```javascript
{
  "presets": [
    "@babel/preset-env"
  ]
}
```

## 3. React with webpack

Till now we have set up the webpack and babel configuration to successfully bundle our javascript code but react is not all javascript, therefore, we need to support react syntax which is the .jsx file. So we need babel again to transpile the code. Let's add some more dependencies for that
``` 
npm i @babel/preset-react --save-dev
```
and also add the configuration to *./babelrc*.
```javascript
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}
```
Now we need to add rules in *webpack.config.js* to make jsx file transpile.

```javascript
const path = require('path');
 
module.exports = {
  entry: path.resolve(__dirname, './src/index.js'),
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
  },
};
```

Now we can write React with jsx code. Let's add the react packages and create a component.

```
npm i react react-dom --save
```

Creating a Home component inside a component folder in src.
```
cd src
mkdir components
touch Home.jsx
```

Home.jsx 

```javascript
import React from 'react';

const Home = () => {
return <div>React Application</div>
}

export default Home
```

Update the `src/index.js`

```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import Home from './components/Home';
 
ReactDOM.render(
  <Home />,
  document.getElementById('app')
);
```

And at last, let's update the index.html

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Hello React</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./bundle.js"></script>
  </body>
</html>
```

Now run `npm start` again and you'll able to see the `Home` component render and there it is how you can set up react with webpack. Although this is a very basic setup, this will give you an idea of how to add more loader and plugin and set it up according to your needs. I'll be writing more about the advanced features and how to make it work with your webpack in the upcoming posts.

Don't forget to give a ❤️ if you liked it and thanks for reading. Happy coding!! 🖥 

*(Note: I have not shown how to use CSS with webpack, I will explain those step in a future post and will also share a boilerplate of react with webpack soon.)*

**(Update: The second part of this post is now available, where I have explained [How to setup Styles (css and sass) with webpack](https://dev.to/deepanjangh/setting-up-css-and-sass-with-webpack-3cg).)**