Implementing history-api-fallback for Webpack Production environment

淺唱寂寞╮ 提交于 2019-12-24 01:43:09

问题


My stack is React/Redux as frontend together with React Router v4 and Firebase Hosting as backend.

Like many others, I also faced the issue of meeting the 404 page not found when users refreshed at a page other than the root URL like https://example.com/about or manually key in the URL https://example.com/about.

I researched many websites and HashBrowser seem to be a workaround for this problem but it is not a complete solution. It does not bring the user to the correct page but instead render the root URL component. Not good enough. Using historyApiFallback: true for production environment seemed to be a bad idea too.

I saw this package, connect-history-api-fallback but it seems to be for a express app.

How can I implement this package in my React app while using Firebase to host my website? Or are there other solutions?


回答1:


I found the solution. This only applies to people deploying React App, using Firebase Hosting to host your single page application. (should work for Angularjs/Vuejs too)

When you first run firebase init, they ask if you want to configure as a single-page app, make sure you select yes. The end result is that they will write this portion to your firebase.json file,

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

it works the same as having

devServer: {
    historyApiFallback: true
},

in your webpack.config.js file to redirect all URLs to the root URL of your application. ("/")

Full implementation of the firebase.json file may look like this,

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

More information may be found in the Firebase Deployment Configuration Documentation.



来源:https://stackoverflow.com/questions/48363292/implementing-history-api-fallback-for-webpack-production-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!