DEV Community

Cover image for Make a React App with Webpack, Babel and Express
Larry Schwall
Larry Schwall

Posted on • Edited on

Make a React App with Webpack, Babel and Express

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:

 mkdir NAME_OF_APP
Enter fullscreen mode Exit fullscreen mode

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)

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:


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);
});
Enter fullscreen mode Exit fullscreen mode

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:

"scripts": {
  "start": "nodemon server/index.js",
  "test": "echo \"Error: no test specified\""
}
Enter fullscreen mode Exit fullscreen mode

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:

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

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:

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}
Enter fullscreen mode Exit fullscreen mode

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:

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

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:

    <!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>
Enter fullscreen mode Exit fullscreen mode

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

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

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:

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"
        }
      }
    ]
  }
};
Enter fullscreen mode Exit fullscreen mode

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":

"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"
}
Enter fullscreen mode Exit fullscreen mode

The next thing to do is refactor our server/index.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);
});
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (10)

Collapse
 
rurouniwallace profile image
rurouniwallace

Another typo:

ReactDOM.render(<Index />,document.getElementbyID('app'));

Should be getElementById. This caused a console error and prevented the text from rendering for me.

Collapse
 
lschwall profile image
Larry Schwall

So sorry. Editing now!

Collapse
 
ayeblinkin profile image
Ayeblinkin

Hey Larry, sorry, one more small typo.
The document.getElementbyId needs the b capitalized. πŸ™‡β€β™‚οΈ
Thank you for this fantastic article!
Helped me both with a work task and personal understanding.
Will definitely reference again in the future! πŸ™πŸ˜

Collapse
 
rurouniwallace profile image
rurouniwallace

Thanks, excellent tutorial, by the way!

Thread Thread
 
lschwall profile image
Larry Schwall

Thank you thank you!

Please share!

Collapse
 
soljin profile image
Jesse Foltz

You have a typo in the step after installing html-webpack-plugin. You say to put the updated code in index.js and it should be webpack.config.js. Could throw people off.

Collapse
 
lschwall profile image
Larry Schwall

GOOD CALL. I didn't even realize I had made that typo. Changed it to the correct place!

Collapse
 
soljin profile image
Jesse Foltz

Thank you! Great barebones tutorial. Exactly what I needed.

Thread Thread
 
lschwall profile image
Larry Schwall

Hey no worries! That’s why I made it. Please share!

Collapse
 
kingman profile image
King-Man • Edited

Just found a little issue when I was trying to install babel. When I run the below command, it gave me an error saying @babel is not a thing.

Below is the command from the article:
npm install --save-dev @babel /core @babel /preset-env @babel /preset-react babel-loader

The solution is to eliminate the space between @babel & /core and do the same for the rest of the @babel.

And thank you for this article, I really appreciate your help!!