我正在创建一个由多个独立子页面组成的 React 应用程序。 我目前有一个独立的“登陆页面”、“菜单页面”和一个“菜单页面”(后两者在某些时候可能会合二为一)。我正在使用 webpack 捆绑我的页面和 webpack 开发服务器以进行本地开发。 菜单页面使用react-router 来进行导航。 这是我的 webpack 设置,以便更好地理解:
{
entry: {
menus: path.resolve(__dirname, "src", "client", "menus.jsx"),
landing: path.resolve(__dirname, "src", "client", "landing.jsx"),
menu: path.resolve(__dirname, "src", "client", "menu.jsx"),
},
output: {
path: path.join(__dirname, outputDirectory),
filename: "[name].bundle.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-react", "@babel/preset-env"],
},
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|jpg|woff|woff2|eot|ttf|svg)$/,
loader: "url-loader?limit=100000",
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "postcss-loader", "sass-loader"],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
devServer: {
port: 3000,
open: true,
historyApiFallback: {
verbose: true,
index: "/landing.html",
rewrites: [
{ from: /^\/menus/, to: "/menus.html" },
{ from: /^\/menu/, to: "/menu.html" },
{ from: /^\/menu\//, to: "/menu.html" },
],
},
proxy: {
"/api": "http://localhost:8080",
},
},
plugins: [
new CleanWebpackPlugin([outputDirectory]),
new HtmlWebpackPlugin({
template: "./src/client/index.html",
chunks: ["menus"],
filename: "menus.html",
}),
new HtmlWebpackPlugin({
template: "./src/client/index.html",
chunks: ["landing"],
filename: "landing.html",
}),
new HtmlWebpackPlugin({
template: "./src/client/index.html",
chunks: ["menu"],
filename: "menu.html",
}),
],
}
我的问题是,当我导航到 /menu/orders
时,historyApiFallback 显示以下日志:
Rewriting GET /menu/preview to /menu.html
Rewriting GET /menu/menu.bundle.js to /menu.html
第一次重写是我所期望的,但是第二次重写让我感到困惑。首先,为什么它试图获取 /menu/menu.bundle.js
?其次,如果我有一个“.”,为什么它要重写路线呢?在路线上?
最后,我怎样才能让它工作,以便 /menu/preview
的工作方式与 /menu
完全相同?
这是我的./src/client/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Locameal</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"/>
</head>
<body>
<div id="app"></div>
</body>
</html>
和./src/client/menu.jsx
import React from "react";
import { render } from "react-dom";
import Menu from "./views/Menu";
import { BrowserRouter } from "react-router-dom";
render(
<BrowserRouter>
<Menu />
</BrowserRouter>,
document.getElementById("app")
);
最佳答案
关于reactjs - Webpack-dev-server HistoryApiFallback 重写子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62276481/