问题
I'm currently creating a project involving flask and webpack. Currently the flask server is able to find the revelant template, but is not able to find the relevant JavaScript.
I have a webpack config for creating the HTML file using the webpack html plugin like so:
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'])],
};
This uses a template called index.html in the src directory which contains the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hellow World</title>
</head>
<body>
<h1>It Works</h1>
</body>
</html>
Which should be bundled by webpack with the following 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());
and print.js:
export default function printMe() {
console.log('I get called from print.js!');
}
The app.py looks like the following:
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)
After running a build, a template is produced in the dist folder with the following content in 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>
I can't workout how it is able to find the template but not able to find the relevant JavaScript.
回答1:
The correct URL for app.bundle.js
as per your configuration is /dist/app.bundle.js
If you want to serve static files from a different folder, you have to set the static_url_path
parameter, in this case to ""
:
app = Flask(__name__, template_folder="dist", static_folder="dist", static_url_path="")
Reference: https://vilimpoc.org/blog/2012/11/21/serving-static-files-from-root-and-not-static-using-flask/
来源:https://stackoverflow.com/questions/48722223/flask-cant-find-static-files-with-webpack