首页 文章

与Flask一起提供create-react-app

提问于
浏览
29

我有一个带有API路径的烧瓶后端,可以通过使用create-react-app样板创建的React单页面应用程序访问 . 当使用create-react-app内置开发服务器时,我的Flask后端工作,没问题 .

现在,我想从我的Flask服务器提供构建的(使用 npm run build )静态反应应用程序 . 构建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

我的问题是:我该如何处理这些文件呢?我想出了这个:

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')

这样,静态资产就能成功提供 . 但它不是一个非常优雅的解决方案 .

另一方面,我可以将其与内置的烧瓶静态实用程序结合使用 . 但我不明白如何配置它 .

我真的不知道如何处理这个问题,以至于它让我重新考虑使用create-react-app,因为它迫使我以一种非常特殊的方式构建我的静态文件夹:没有办法我要改变应用程序从服务器请求静态内容的方式 .

总体而言:我的解决方案足够强大吗有没有办法使用内置的烧瓶功能来提供这些资产?有没有更好的方法来使用create-react-app?任何输入都表示赞赏 . 如果需要,我可以提供更多信息 .

谢谢阅读 !

1 回答

  • 32
    import os
    from flask import Flask, send_from_directory
    
    app = Flask(__name__, static_folder='react_app/build')
    
    # Serve React App
    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def serve(path):
        if path != "" and os.path.exists("react_app/build/" + path):
            return send_from_directory('react_app/build', path)
        else:
            return send_from_directory('react_app/build', 'index.html')
    
    
    if __name__ == '__main__':
        app.run(use_reloader=True, port=5000, threaded=True)
    

    这就是我最终的结果 . 所以基本上捕获所有路由,测试路径是否为文件=>发送文件=>否则发送index.html . 这样你就可以从你希望的任何路线重新加载反应应用程序,它不会破坏 .

相关问题