为 Webpack 生产环境实现 history-api-fallback

Implementing history-api-fallback for Webpack Production environment

我的堆栈是 React/Redux 作为前端,React Router v4 和 Firebase Hosting 作为后端。

像许多其他人一样,我也遇到了当用户在根 URL 以外的页面刷新时遇到找不到 404 页面的问题,例如 https://example.com/about or manually key in the URL https://example.com/about

我研究了很多网站,HashBrowser 似乎是解决这个问题的方法,但它不是一个完整的解决方案。它不会将用户带到正确的页面,而是呈现根 URL 组件。还不够好。在生产环境中使用 historyApiFallback: true 似乎也是一个坏主意。

我看到了这个包,connect-history-api-fallback但它似乎是一个 express 应用程序。

在使用 Firebase 托管我的网站时,如何在我的 React 应用程序中实施此包? 或者还有其他解决方案吗?

我找到了解决方案。这仅适用于部署 React App、使用 Firebase Hosting 托管您的单页应用程序的人员。 (应该也适用于 Angularjs/Vuejs)

当您第一次 运行 firebase init 时,他们会询问您是否要配置为单页应用程序,确保您 select .最后的结果是他们会把这部分写到你的firebase.json文件中,

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} 

它的工作原理与

相同
devServer: {
    historyApiFallback: true
},

在您的 webpack.config.js 文件中将所有 URL 重定向到应用程序的根目录 URL。 ("/")

firebase.json 文件的完整实现可能如下所示,

{
  "hosting": {
    "public": "public",
    "rewrites": [{
      "source": "**",
      "destination": "/index.html"
    }],
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

可以在 Firebase Deployment Configuration Documentation 中找到更多信息。