Deploy Webpack React app (not using create-react-app) to Heroku

If you are starting on web-development in 2018, I am sure all or at least most of your frontend projects are by default built and bundled using Webpack.

To setup Webpack app, please find this article https://www.freecodecamp.org/news/part-1-react-app-from-scratch-using-webpack-4-562b1d231e75/

This post is mainly aimed at people who are already using Webpack applications in their personal, GitHub or even client projects to successfully deploy and host their web applications on Heroku.

1. Build an express server

The first step is to build a simple express server to serve your application.

What is an Express server you ask?
An Express is a web-application framework that basically runs on a node environment. In our case it serves our application from a port available in the same environment.

We are going to build a simple standard express server to serve our index.html file after Webpack generated all the bundles.


const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
// the __dirname is the current directory from where the script is running
app.use(express.static(__dirname));
// send the user to index html page inspite of the url
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port);

In your webpack.config.js file, if you have the following code, you will see a bundle.js generated at the root of your application.


module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
}
}

Now that we are here finally, close to deployment, we need to add two lines of script in our package.json file. Add these two following commands under the scripts section.

"scripts": {
  "start": "node server.js", // serves the application
  "heroku-postbuild": "webpack -p" // runs after installation
},

 

Posted by justinpham

Leave a Reply