Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running npm run build in Heroku to serve a flask backend react frontend app

I've got a Flask app that also serves a React frontend by serving files from a /build folder that gets generated when I run npm run build.

My directory structure:

.
|-client/
|  |build/
|    |static/
|
|-server/
|  |main.py

In order to deploy my app to Heroku, I have to...

  1. cd into client
  2. run npm run build in order to generate the new static build of the react app
  3. commit the changes to git

This works, but it's definitely a pain. It creates HUGE diffs in Github when we create PRs.

I'm wondering, is it possible to run npm run build in the Heroku pipeline? I think the Procfile is the way to go. I've tried a couple of things like adding

npm: cd client && npm run build
web: flask db upgrade; gunicorn wsgi:app

to no avail.

like image 410
Seanyboy Lee Avatar asked Dec 26 '20 00:12

Seanyboy Lee


1 Answers

This is more a Heroku question than a Flask question.

Yes, it's possible to run npm run build as part of your deployment.

Make sure that your app uses the Node.js buildpack along with the Python buildpack. Then create a package.json in your project root (sibling to server/ and client/). In that, add (other content of package.json omitted):

{
  "cacheDirectories": [
    "client/node_modules"
  ],
  "scripts": {
    "heroku-postbuild": "cd client && npm install && npm run build"
  }
}

Heroku will automatically pick up that build script and run the specified command(s). It'll also cache the node_modules in the client/ directory. The documentation around this is a bit sparse, but you can find the relevant info here and here.

You'll also want to remove and ignore the JS build directories from Git, as they're not needed any more. Just make sure the directory(/ies) used for storing the JS build artifacts exist at the time when Heroku runs the postbuild script.

I wrote a more in-depth guide about this on here.

like image 51
Karl Sutt Avatar answered Nov 04 '22 23:11

Karl Sutt