我有一个带有API路由的Flask后端,可由使用create React app创建的React单页应用程序访问.使用create react app dev服务器时,我的Flask后端工作正常.
我想从我的Flask服务器上安装(使用npm run build
个)静态React应用程序.构建React应用程序将导致以下目录 struct :
- 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
我应该如何提供这些文件?我想到了这个:
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')
通过这种方式,可以成功地为静态assets资源 提供服务.
另一方面,我可以将其与内置的静态工具结合起来.但我不明白如何配置它.
我的解决方案足够健壮吗?有没有办法使用内置的Flask 功能来服务这些assets资源 ?有没有更好的方法来使用create react应用程序?