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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With