How to use Local Builds on Heroku

Written by domantaspelaitis | Published 2019/09/07
Tech Story Tags: local-builds-on-heroku | heroku | tutorial | latest-tech-stories | single-page-web-applications | deploy-any-spa-to-heroku | npm-packages | development-dependencies

TLDR A simple way to deploy any SPA to Heroku is to skip the build process completely. The build process fails on Heroku because of some of the packages that Heroku failed to use for some reason. To use this deployment flow all you have to do is build your app locally and push it to the Heroku platform. It might help you if you can build your application locally without any problems, but if you are just hacking something and can’t figure out why your builds fail this might do the job.via the TL;DR App

I’ve seen a few tutorials, how to deploy single page web applications on Heroku, but I’ve really struggled to do it myself, because I wanted to do it a bit differently. I found a way how to deploy any SPA to Heroku using local builds.

Why

Well, the problem we faced was that our app had some npm packages (node-sass to be specific) that Heroku failed to use for some reason. So this deployment flow might help you if you can build your application locally without any problems, but the build process fails on Heroku.

How

First of all, we will need an express app that will serve our web app. It should look something like this:
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(path.join(__dirname,'/build')))app.get('*', (req,res) => {res.sendFile(path.join(__dirname + '/build/index.html'))})
app.listen(port, () => console.log('App listening on port ' + port))
By default, Heroku installs development dependencies. And if we are trying to deploy an app that is already built we can skip the installation of development dependencies. This can be done by using the following command:
heroku config:set NPM_CONFIG_PRODUCTION=true YARN_PRODUCTION=true
Now if your app uses some of the dependancies that are development dependencies the build on Heroku might still fail. What we want to do is skip building process completely. And this can be done by adding the following npm script to your package.json
heroku-postbuild”: “echo Skip build on Heroku
Now heroku will use this script instead of the default build script. And this script allows to skip the build process completly.
Finally, we add a Procfile with text:
"web: node app $PORT"
Notice, name this file “Procfile” and don’t use any file extensions. This is Heroku specific file.
Finally, to use this deployment flow all you have to do is build your app locally and push it to Heroku.
I would not recommend this approach in production, but if you are just hacking something and can’t figure out why your builds fail this might do the job.

Published by HackerNoon on 2019/09/07