【问题标题】:Implementing history-api-fallback for Webpack Production environment为 Webpack 生产环境实现 history-api-fallback
【发布时间】:2018-06-30 00:06:37
【问题描述】:

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

与许多其他人一样,当用户在根 URL 以外的页面(如 https://example.com/about 或手动键入 URL https://example.com/about)刷新页面时,我也遇到了找不到 404 页面的问题。

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

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

在使用 Firebase 托管我的网站时,如何在我的 React 应用中实现这个包? 还是有其他解决方案?

【问题讨论】:

  • 你是用firebase-cli部署的吗?如果您这样做了,那么它会询问您是否要部署为 SPA,这可以解决您的问题。但当然你需要先运行“npm run build”来获取你的构建文件夹,然后在 firebase-cli 中指定该文件夹
  • 是的,我正在使用 firebase-cli 部署我的应用程序。是的,我确实将部署指定为 SPA。当我运行“npm run build”时,我只得到 bundle.js 文件,没有构建文件夹。我将所有文件,即 index.html、bundle.js 放在“公共”文件夹中。澄清一下,构建文件夹中应该有哪些文件?

标签: reactjs redux react-router connect browser-history


【解决方案1】:

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

当您第一次运行firebase init 时,他们会询问您是否要配置为单页应用,请确保您选择yes。最终结果是他们会将这部分写入您的 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 中找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多