webpack-dev-server historyApiFallback在多级路由的情况下不起作用



我正在使用historyApiFallback: true将所有不存在的URL重定向到索引页面。它适用于一级路由,例如本地主机:8080/abc。但是当我尝试本地主机:8080/abc/xyz时,我在浏览器控制台中出现错误,上面写着

http://localhost:8080/abc/scripts/bundle.js 404(未找到(

Webpack 配置是

const path = require('path');
module.exports = {
    entry:"./src/app.js",
    output:{
        path:path.join(__dirname,'public','scripts'),
        filename:'bundle.js'
    },
    module:{
        rules:[{
            test:/.js$/,
            exclude:/node_modules/,
            loader:'babel-loader'
        }]
    },
    devServer:{
        contentBase:path.join(__dirname,'public'),
        publicPath:'/scripts/',
        historyApiFallback: true
    }
}

索引页

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div id="app">
        hello
    </div>
</body>
<script type="text/javascript" src="scripts/bundle.js"></script>
</html>

文件夹结构为

-node_modules/
-public/
    -scripts/
    -index.html
-src/
    -app.js
-package.json
-webpack.config.js

我错过了什么?

html 中脚本标记中缺少正斜杠导致了问题。这帮助我解决了问题。

您可以使用

rewrites进一步细化行为。从文档中:

historyApiFallback: {
  rewrites: [
    { from: /^/$/, to: '/views/landing.html' },
    { from: /^/subpage/, to: '/views/subpage.html' },
    { from: /./, to: '/views/404.html' }
  ]
}

最新更新