本文介绍了在 Heroku 中运行 npm run build 来为 Flask 后端反应前端应用程序提供服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Flask 应用程序,它也通过提供来自 /build 文件夹中的文件来提供 React 前端,该文件夹在我运行 npm run build 时生成.>

我的目录结构:

.|-客户端/||构建/||静态/||-服务器/||main.py

为了将我的应用程序部署到 Heroku,我必须...

  1. cd 进入客户端
  2. 运行 npm run build 以生成 React 应用程序的新静态构建
  3. 提交对 git 的更改

这行得通,但肯定很痛苦.当我们创建 PR 时,它会在 Github 中产生巨大的差异.

我想知道,是否可以在 Heroku 管道中运行 npm run build?我认为 Procfile 是要走的路.我已经尝试了一些事情,比如添加

npm: cd client &&npm 运行构建网络:烧瓶数据库升级;gunicorn wsgi:app

无济于事.

解决方案

这更像是 Heroku 问题而不是 Flask 问题.

是的,可以将 npm run build 作为部署的一部分运行.

确保您的应用程序使用 Node.js buildpack 和 Python buildpack.然后在您的项目根目录中创建一个 package.json(与 server/和 client/同级).其中,添加(省略package.json的其他内容):

{缓存目录":[客户端/节点模块"],脚本":{heroku-postbuild":cd 客户端 &&"npm 安装 &&npm 运行构建"}}

Heroku 将自动选取该构建脚本并运行指定的命令.它还将在 client/目录中缓存 node_modules.围绕此的文档有点稀疏,但您可以找到相关信息 此处此处.

您还需要从 Git 中删除并忽略 JS 构建目录,因为不再需要它们.只需确保在 Heroku 运行 postbuild 脚本时存在用于存储 JS 构建工件的目录(/ies).

我在 这里.

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.

解决方案

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.

这篇关于在 Heroku 中运行 npm run build 来为 Flask 后端反应前端应用程序提供服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:32