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

webpack-dev-server historyApiFallback not working in case of multilevel routing

我正在使用 historyApiFallback: true 将所有不存在的网址重定向到索引页面。它适用于一级路线,比如 localhost:8080/abc 。但是当我尝试 localhost:8080/abc/xyz 时,浏览器控制台出现错误

http://localhost:8080/abc/scripts/bundle.js 404 (Not Found)

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

我错过了什么?

您可以使用 rewrites 进一步优化行为。来自 the documentation:

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

html 中的脚本标记中缺少正斜杠是导致问题的原因。 This帮我解决了问题。