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

北慕城南 提交于 2021-01-04 06:51:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/65452878/running-npm-run-build-in-heroku-to-serve-a-flask-backend-react-frontend-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!