【问题标题】:webpack-dev-server historyApiFallback not working in case of multilevel routingwebpack-dev-server historyApiFallback 在多级路由的情况下不起作用
【发布时间】:2018-03-10 10:08:18
【问题描述】:

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

http://localhost:8080/abc/scripts/bundle.js404(未找到)

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

我错过了什么?

【问题讨论】:

    标签: webpack-dev-server


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我已添加 - 重写:[ { from: /^\/[a-z]*/, to: '/index.html' }, ] 现在索引是从 localhost:8080/abc /xyz 但 bundle.js 不包含 app.js 编写的编译代码,而是包含 html 内容。
      • 很高兴您的 devServer 现在正在工作。听起来你有一个新问题,那将是一个不同的问题。我使用html-webpack-plugin来打包html内容。
      • 使用重写我们可以有特定的回退,但它并没有解决我的问题。后来我意识到出了什么问题。它只是在 html 的脚本标记的开头添加一个正斜杠,这与 historyApiFallback: true 配合得很好。
      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 2019-04-22
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2017-01-14
      • 2018-08-20
      • 2018-05-21
      相关资源
      最近更新 更多