Flask无法找到Vue构建的应用程序的资源文件(css,js ...)

3

我在vue的构建设置和Flask的静态文件夹设置上遇到了问题。我已经尝试了几种情况来设置Flask的静态文件夹,但只有其中一种情况适用于我。我不知道为什么。

// Build setting from vue.config.js

module.exports = {
    publicPath: process.env.NODE_ENV === 'production'
        ? '/dist/'
        : '/'
}

所以我的index.html文件中的资源文件src和href为:
<script src=/dist/js/app.f4f6d455.js></script>

这是我的尝试和结果。

案例1:错误!

// Flask Setting
app = Flask(__name__, template_folder = "./dist")

//Directory Structure
/project
    /dist
        /js
            app.f4f6d455.js
        index.html
    flask.py

结果:无法加载资源 > http://127.0.0.1:5000/dist/js/app.f4f6d455.js

案例2:错误!

将资源复制到“static / dist”中,因为Flask的默认static_folder是“static”,并保留dist文件夹以更好地澄清错误消息。

// Flask Setting
app = Flask(__name__,
        template_folder = "./dist")

//Directory Structure
/project
    /dist
        /js
            app.f4f6d455.js
        index.html
    /static
        /dist
            /js
                app.f4f6d455.js
    flask.py

结果:无法加载资源 > http://127.0.0.1:5000/dist/js/app.f4f6d455.js

情况3:有效!

将flask的static_folder更改为“dist”

// Flask Setting
app = Flask(__name__,
    static_folder = "dist",
    template_folder = "./dist")

//Directory Structure
/project
    /dist
        /js
            app.f4f6d455.js
        index.html
    flask.py

我认为当Flask试图查找其资产文件时,这是根路径的问题。但是Case 3在Case 2不起作用时有效。如果Case 2的根路径是'http://127.0.0.1:5000/static',那么它应该能够工作。有人能帮我理解这个问题吗?
提前感谢。

我觉得你可能把publicPathoutputDir搞混了。加载应用程序的默认页面应该使用哪个URL路径?是http://localhost:5000/还是http://localhost:5000/dist/ - undefined
@Phil 谢谢你的评论。默认页面是 'index.html',位于 'project/dist/index.html',此外我的Flask应用程序表示 '/project' 是其 app.root_path。 - undefined
1个回答

1
如果您希望前端应用的资产从http://localhost:5000/dist提供,请配置Flask应用程序中的static_url_path以匹配。
app = Flask(__name__, 
  static_folder="whatever-folder-you-want", 
  static_url_path="/dist")

你还应该添加一个全匹配的端点,将所有未匹配的请求路由到你的SPA。
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return app.send_static_file("index.html")

请参考https://flask.palletsprojects.com/en/1.1.x/patterns/singlepageapplications/


如果您想使用Flask的默认静态文件夹和路径,则需要更改Vue配置为:
module.exports = {
  outputDir: "path/to/static", // the static folder in your Flask app
  publicPath: process.env.NODE_ENV === 'production'
    ? "/static/"
    : "/"
}

如果您想在构建Vue应用程序后将dist文件夹复制到Flask的static文件夹中,可以将publicPath更改为/static/dist/
module.exports = {
  publicPath: process.env.NODE_ENV === 'production'
    ? "/static/dist/"
    : "/"
}

谢谢你的建议!我猜想Vue和Flask之间的静态文件夹设置应该明确匹配。即使index.html文件存在于Vue指定的文件夹中,如果Flask的静态文件夹没有指定相应位置,渲染将会失败。再次感谢! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接