我正在尝试使用 Flask 发送 html 视图(模板)并为前端使用 React,但我在前端设置
webpack-dev-server
时遇到问题。我的困惑是,我的 Flask 应用程序在端口 5000 上运行并在该端口上发送视图。 WebpackdevServer 在端口 8080 上启动。
我知道 webpack 开发服务器也为内存不足的包提供服务,但我如何使用它来创建热模块替换。我已经阅读了其他答案,并且将 webpack watch 与开发服务器结合使用似乎在技术上不正确。
我需要做什么才能让 Flask html 模板上的
script
标签加载由 webpack 或 webpack 开发服务器生成的包文件?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<div id="main"></div>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script defer src="../js/main.bundle.js" type="text/javascript"></script>
</body>
</html>
//webpack dev config
const ab_path = path.resolve(__dirname, '../', 'static/', 'js/');
module.exports = merge.merge(common, {
entry: ["./src/index.js"],
output: {
filename: '[name].bundle.js',
path: path.join(process.cwd(), "../static/js")
},
// o
devtool: 'inline-source-map',
devServer: {
hot: true,
open: true,
static: path.resolve(ab_path),
},
plugins: [
new ESLintPlugin()
],
mode: "development"
});
我运行命令 `webpack-dev-server --config /path/to/dev/config 但它似乎除了打开一个新选项卡到 localhost:8080 之外没有做任何事情
配置 Flask 为 React 应用程序提供服务:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
更新您的 HTML 模板:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<div id="main"></div>
<meta name="viewport" content="width=device-width, initial-scale=1">
{% if DEBUG %}
<script defer src="http://localhost:8080/main.bundle.js" type="module"></script>
{% else %}
<script defer src="{{ url_for('static', filename='js/main.bundle.js') }}"></script>
{% endif %}
</head>
<body>
</body>
</html>
更新 Webpack 开发配置:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path');
module.exports = merge(common, {
entry: ['./src/index.js'],
output: {
filename: '[name].bundle.js',
path: path.join(process.cwd(), 'dist'),
publicPath: 'http://localhost:8080/', // Important for webpack-dev-server
},
devtool: 'inline-source-map',
devServer: {
hot: true,
open: true,
static: path.resolve(process.cwd(), 'dist'),
},
mode: 'development',
});
更新Webpack生产配置:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path');
module.exports = merge(common, {
entry: ['./src/index.js'],
output: {
filename: '[name].bundle.js',
path: path.join(process.cwd(), 'static', 'js'),
},
mode: 'production',
});