Flask找不到webpack

时间:2018-02-10 15:14:10

标签: javascript python flask webpack html-webpack-plugin

我目前正在创建一个涉及烧瓶和网络包的项目。目前,烧瓶服务器能够找到相关的模板,但无法找到相关的JavaScript。

我有一个webpack配置,用于使用webpack html插件创建HTML文件,如下所示:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    entry: {app: './src/index.js', print: './src/print.js'},
    output: {filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist')},
    plugins: [new HtmlWebpackPlugin({template:"./src/index.html"}), new CleanWebpackPlugin(['dist'])],
};

这在src目录中使用名为index.html的模板,其中包含以下内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hellow World</title>
</head>
<body>
<h1>It Works</h1>
</body>
</html>

哪个应该通过webpack与以下javascript捆绑在一起, index.js:

import _ from 'lodash';
import printMe from './print.js';

function component() {
    let element = document.createElement('div');
    let btn = document.createElement('button');

    // lodash now imported
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    // new button
    btn.innerHTML = 'Click me and check the console!';
    btn.onclick = printMe;

    element.appendChild(btn);

    return element;
}

document.body.appendChild(component());

和print.js:

export default function printMe() {
  console.log('I get called from print.js!');
}

app.py如下所示:

from flask import Flask, render_template
app = Flask(__name__, template_folder="dist/", static_folder="dist/")


@app.route("/")
def index():
    """
    renders basic index page
    :return: template
    """
    return render_template("index.html")


# app entry point
if __name__ == "__main__":
    app.run(debug=True)

运行构建后,会在dist文件夹中生成一个模板,其中包含index.html中的以下内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hellow World</title>
</head>
<body>
<h1>It Works</h1>
<script type="text/javascript" src="app.bundle.js"></script><script type="text/javascript" src="print.bundle.js"></script></body>
</html>

我无法锻炼如何找到模板但无法找到相关的JavaScript。

1 个答案:

答案 0 :(得分:4)

根据您的配置,app.bundle.js的正确网址为/dist/app.bundle.js

如果您要从其他文件夹提供静态文件,则必须将static_url_path参数设置为""

app = Flask(__name__, template_folder="dist", static_folder="dist", static_url_path="")


参考:https://vilimpoc.org/blog/2012/11/21/serving-static-files-from-root-and-not-static-using-flask/