Make a React App with Webpack, Babel and Express
Tags: react, babel, webpack, express
Published: 2020-10-27 02:06:50

### INTRODUCTION

Have you ever wanted to build your own Node.js application? Well look no further. This guide is going to help you!
***
### THE ESSENTIALS

The first step in creating any app is to give it a home. In your terminal, you need to issue the following command: 
```js
 mkdir NAME_OF_APP
 ```

***NOTE***: NAME_OF_APP is the name of the application you are making! Have some fun with it!

After creating your home for your new app, go ahead and *cd* into your directory. Then make sure you have node and npm: 

>node -v
>npm -v

(if you do not have these installed find them here: [NPM](https://www.npmjs.com/get-npm))

Now lets initialize the project with: 
> npm init

or

> npm init -y

Adding the "-y" flag will allow you to answer yes to all the options that init will prompt you with. If you don't know what you want, I suggest add the "-y" flag. 

Once all of these steps are complete, you should see a file in your structure called: ***package.json***. If you have this in your file structure, then you have done the steps right so far!

***

### STEP ONE: *Express*

Lets make a server! In this tutorial we will be using something called Express.js. This a framework that is especially popular with creating RESTful APIs and routes.

To install express, type the following into your terminal:

> npm install --save express

node_modules folder will then be visible in your file structure. Any other dependencies can be found in this folder. 

To get your server running, we need to do a few things first.
>Set up a folder called **Server**. Inside this folder create a file called  **index.js**.  Add the following to your file: 

```js

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const mockResponse = {
  foo: 'bar',
  bar: 'foo'
};
app.get('/api', (req, res) => {
  res.send(mockResponse);
});
app.get('/', (req, res) => {
 res.status(200).send('Hello World from the server!');
});
app.listen(port, function () {
 console.log('App listening on port: ' + port);
});
```
This completes the basic express server set up. Lets take a quick look at the **package.json** to get our server to start.

We need to install nodemon to keep our server running in the meantime: 
>npm i -g nodemon

 Add the following to your **"scripts"** in package.json:

```js
"scripts": {
  "start": "nodemon server/index.js",
  "test": "echo \"Error: no test specified\""
}
```

Now issue this command in your terminal: 
>npm run start

You should see in your browser "Hello World from server!"  at *localhost:3000*. 

***
### STEP TWO: *Webpack*

The first step to get webpack to work is to run the following code: 

> npm install --save-dev webpack webpack-cli

In **package.json**,  add this to your script: 

```js
"scripts": {
  "start": "node server/index.js",
  "build": "webpack --mode production",
  "test": "echo \"Error: no test specified\""
}
```

The second part is to this is to create a folder in the root called **src**. Most of the code in this application will exist here. Inside of this folder, you can place an **index.js** file that remains empty. 

Now run: 

>npm run build

This will create a dist folder where your minified project will live. You do not need to modify this file in anyway.

***
### STEP THREE: *Babel*

In react, certain files end with the extension *.jsx*. Babel helps compile these type of files into *.js*. 

To install babel run the following in the terminal: 

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

In the root of your file structure, add a file name **.babelrc** and add the following snippet:
```js
{
	"presets": ["@babel/preset-env", "@babel/preset-react"]
}
```

The next step to getting babel integrated is into your file structure is to create a **webpack.config.js** in the root of your file structure. This is because webpack needs to tell babel to compile the *.jsx* and *.js* files before being bundled. 

Inside of the config file add this: 

```js
	module.exports = {
		module: {
			rules: [
				{
					test: /\.(js|jsx)$/,
					exclude: /node_modules/,
					use: {
						loader: "babel-loader"
					}
				}
			]
		}
	};
```
***

### STEP THREE: *React*

 To install react, run the following: 

>npm install --save react react-dom

In the folder **/src**, add an **index.html**.  In this file you need to add: 

```html
	<!DOCTYPE html>
		<html lang="en">
			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width, initial-scale=1, maximun-scale=1">
				<meta http-equiv="X-UA-Compatible" content="ie=edge">
				<title>React Boilerplate</title>
			</head>
			<body>
				<div id="app"></div>
			</body>
		</html>
```

In the folder **/src**, add an **index.js**.  In this file you need to add: 

```js
	import React from 'react';
	import ReactDOM from 'react-dom';
	const Index = () => {
		return <div>WELCOME TO REACT APP!</div>;
	};
	ReactDOM.render(<Index />,document.getElementById('app'));
```

In order to get your React app and webpack to work together, we want to install something called: *html-webpack-plugin*. 

To get this to work, install the following: 

> npm install --save-dev html-webpack-plugin

and paste this into **webpack.config.js**: 

```js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');
const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html", 
  filename: "./index.html"
});
module.exports = {
  entry: "./src/index.js",
  output: { // NEW
    path: path.join(__dirname, 'dist'),
    filename: "[name].js"
  }, // NEW Ends
  plugins: [htmlPlugin],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};
```

The last and final step to getting this React App to work properly, you need to connect react with express. 

In your **package.json** add a *dev* under **"scripts"**: 

```js
"scripts": {
  "start": "node server/index.js",
  "dev": "webpack --mode development && node server/index.js",
  "build": "webpack --mode production",
  "test": "echo \"Error: no test specified\" && exit 1"
}
```

The next thing to do is refactor our **server/index.js**: 

```js
const express = require('express');
const path = require('path'); // NEW

const app = express();
const port = process.env.PORT || 3000;
const DIST_DIR = path.join(__dirname, '../dist'); // NEW
const HTML_FILE = path.join(DIST_DIR, 'index.html'); // NEW
const mockResponse = {
  foo: 'bar',
  bar: 'foo'
};
app.use(express.static(DIST_DIR)); // NEW
app.get('/api', (req, res) => {
  res.send(mockResponse);
});
app.get('/', (req, res) => {
 res.sendFile(HTML_FILE); // EDIT
});
app.listen(port, function () {
 console.log('App listening on port: ' + port);
});
```
Now run: 

>npm run dev

You should see "WELCOME TO REACT APP! at localhost:3000!
***

***A couple things to note with this tutorial. ***
1. This guide is meant to speed through the bare bones of getting your app up and running. It is up to you to learn the logic behind each of these steps. 
2. Create a .gitignore file to ignore your bundled files. This will make life easier if working in a team for your application. Include the following and anything else you want to hide from a user:
	> /client/dist/
	>.env

***

### Conclusion

Thanks for checking this out. If this helped, leave a like or bookmark for a quick reference!