Author avatar

Kimaru Thagana

Deploying to Heroku with Webpack

Kimaru Thagana

  • Nov 9, 2020
  • 8 Min read
  • 177 Views
  • Nov 9, 2020
  • 8 Min read
  • 177 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

Webpack is a tool used in JavaScript applications for dependency management. By traversing all the imports in your app, webpack creates a dependency graph consisting of all the assets needed by your app. This dependency graph is then used to generate one or more files called bundles.

WebPack Core Concepts

Entry

The entry point pinpoints the module that webpack should start with when creating its internal dependency graph. By default, webpack uses ./src/index.js.

Output

The output specifies the location that webpack should use to emit bundles and how to name them. By default, webpack uses ./dist/main.js for the main output file and ./dist folder for other generated files.

Loaders

Loaders are webpack's way of allowing developers to bundle files other than JavaScript and JSON that Webpack does not understand out of the box.

Setting Up the App

In order to continue, make sure you have the latest nodeJS and npm installed on your computer.

Create a new folder named deploy-react-webpack and navigate to the folder.

1
2
mkdir deploy-react-webpack
cd deploy-react-webpack

Initialize the project with default options.

1
npm init -y

This creates a package.json file.

Install the required ReactJs packages.

1
npm i react react-dom

Babel

Babel converts ES5 and ES6 syntax used in ReactJs to a backwards-compatible version of JavaScript that is supported by both older and newer browsers.

Install Babel:

1
npm i -D @babel/core babel-loader @babel/preset-env @babel/preset-react

Install webpack and webpack-cli:

1
npm i -D  webpack webpack-cli webpack-dev-server

Configuring Babel

Create a new file at the project root named .babelrc.

1
touch .babelrc

Add the following code to the file and save.

1
2
3
4
5
{
  "presets": [
      "@babel/preset-env","@babel/preset-react"
   ]
}
json

Configure Webpack

Create a new file at the project root named webpack.config.js.

Add Components for Processing HTML

1
npm i html-webpack-plugin html-loader --save-dev
1
touch webpack.config.js

Add the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = {
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader"
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: "./src/index.html",
            filename: "./index.html"
        })
    ]
};
js

entry tells webpack where to start when bundling your application. The test rule specifies the file extensions where the babel-loader can be used while excluding files in the node_modules.

Creating the React App

In this stage you will create the actual React app that users can interact with.

Create index.html inside src.

1
2
3
mkdir src
cd src
touch index.html

Add the following code to index.html.

1
2
3
4
5
6
7
8
9
10
<html lang="en">
<head>
    <meta charset="utf-8">
     <meta name="viewport" content="width=device-width,initial-scale=1, shrink-to-fit=no">
    <title>How To Deploy React Js With Babel On Heroku</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
html

Inside src, create a file named index.js.

1
touch index.js

Add the following code.

1
2
3
4
5
6
7
8
9
10
11
12
import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component{
    render(){
        return(
            <div>
                Hello World !
            </div>
        )
    }
}
ReactDOM.render(<App/>, document.getElementById("root"));
jsx

This creates a simple React hello world component.

Replace the following code in your package.json.

1
2
3
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
},
json

with

1
2
3
4
5
"scripts": {
    "dev": "webpack serve",
    "start": "node server.js",
    "build": "webpack --mode production"
  },
json

The dev command is used to run the app in development mode. The start command is used by Heroku to serve files in production.

Your package.json should look like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
  "name": "deploy-react-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack serve",
    "start": "node server.js",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.3",
    "@babel/preset-env": "^7.12.1",
    "@babel/preset-react": "^7.12.5",
    "@webpack-cli/serve": "^1.0.1",
    "babel-loader": "^8.1.0",
    "html-loader": "^1.3.2",
    "html-webpack-plugin": "^4.5.0",
    "webpack": "^5.4.0",
    "webpack-cli": "^4.1.0",
    "webpack-dev-server": "^3.11.0"
  }
}
json

Adding Express To Serve Files in Heroku

Install Express using the following command:

1
npm install express

Create a file in the project root named server.js and add the following code:

1
2
3
4
5
6
7
8
9
10
11
var path = require('path');
var express = require('express');

var app = express();

app.use(express.static(path.join(__dirname, 'dist')));
app.set('port', process.env.PORT || 8080);

var server = app.listen(app.get('port'), function() {
  console.log('listening on port ', server.address().port);
});
js

Preview Project Locally

Run the following command to launch the project locally.

1
npm run dev

Open the following link in your browser window:

1
http://127.0.0.1:8080/

You should see a page like this:

hello world

Build Project for Production

1
npm run build

Deploy to Heroku

Create an account on Heroku and confirm your email address.

Install Heroku CLI:

1
npm install -g heroku

Confirm that the Heroku CLI is installed by running:

1
heroku --version

You should see your Heroku CLI version.

Log in to Heroku by executing the command below.

1
heroku login

Running this command will open the Heroku site on your browser, where you can log in.

Set up a Git repository in the project root.

1
git init

Ignore Node modules in Git.

1
touch .gitignore

Add the following line to the file:

1
node_modules
1
git add .
1
git commit -m "initial commit"

Create a Heroku app.

1
heroku create

Publish to Heroku.

1
git push heroku master

Once the build succeeds, you can go to your Heroku apps dashboard and open your app or open the link in your console.

Once you open the link, your app should look like this:

Build preview

All done!

Conclusion

Mastery of this skill is vital in roles such as frontend development and devOps leaning towards frontend projects.

You can learn more about webpack at the webpack official documentation website. You can also learn more about deploying apps on Geroku here.

2