我有一个带有API路由的Flask后端,可通过使用create-react-app创建的React单页应用程序访问。当使用create-react-app开发服务器时,我的Flask后端可以工作。
我想npm run build
从我的Flask服务器提供内置的(使用)静态React应用程序。构建React应用会导致以下目录结构:
- build
- static
- css
- style.[crypto].css
- style.[crypto].css.map
- js
- main.[crypto].js
- main.[crypto].js.map
- index.html
- service-worker.js
- [more meta files]
通过[crypto]
,我的意思是在构建时所产生的随机生成的字符串。
收到index.html
文件后,浏览器将发出以下请求:
- GET /static/css/main.[crypto].css
- GET /static/css/main.[crypto].css
- GET /service-worker.js
How should I serve these files? I came up with this:
from flask import Blueprint, send_from_directory
static = Blueprint('static', __name__)
@static.route('/')
def serve_static_index():
return send_from_directory('../client/build/', 'index.html')
@static.route('/static/<path:path>') # serve whatever the client requested in the static folder
def serve_static(path):
return send_from_directory('../client/build/static/', path)
@static.route('/service-worker.js')
def serve_worker():
return send_from_directory('../client/build/', 'service-worker.js')
This way, the static assets are successfully served.
On the other hand, I could incorporate this with the built-in Flask static utilities. But I do not understand how to configure this.
Is my solution robust enough? Is there a way to use built-in Flask features to serve these assets? Is there a better way to use create-react-app?
接受的答案对我不起作用。我用过了