为什么 React Webpack 生产版本显示空白页面?
我想通了,我在没有设置本地服务器的情况下使用 browserHistory。如果我将其更改为 hashHistory,它会起作用。要使用 react-router 浏览器历史记录在本地测试 webpack 生产,我需要这样做 配置服务器:
您的服务器必须准备好处理真实的 URL。当应用程序首次在 / 加载时,它可能会工作,但是当用户浏览并在 /accounts/23 刷新时,您的 Web 服务器将收到对 /accounts/23 的请求。您将需要它来处理该 URL 并在响应中包含您的 JavaScript 应用程序。
Express 应用程序可能如下所示:
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
// serve static assets normally
app.use(express.static(__dirname + '/public'))
// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port)
console.log("server started on port " + port)
以防万一有人使用带有浏览器历史记录的 react-router 部署到 firebase,请执行以下操作:
{
"firebase": "<YOUR-FIREBASE-APP>",
"public": "<YOUR-PUBLIC-DIRECTORY>",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
利用
import { HashRouter } from 'react-router-dom';
代替
import { BrowserRouter} from 'react-router-dom';
并且不要忘记在您的路线代码中替换它
<HashRouter>
...
</HashRouter>
改变
import {BrowserRouter as Router} from 'react-router-dom'
到:
import {HashRouter as Router} from 'react-router-dom'
在App.js 中帮助我解决了 create-react-app 项目中的相同问题。
GitHub Pages 不支持在底层使用 HTML5pushState
历史 API 的路由器(例如,使用 的 React 路由器browserHistory
)。这是因为当 url 有一个新的页面加载时http://user.github.io/todomvc/todos/42
,其中/todos/42
是前端路由,GitHub Pages 服务器返回 404,因为它对 一无所知/todos/42
。如果您想将路由器添加到托管在 GitHub Pages 上的项目,这里有几个解决方案:
- 您可以从使用 HTML5 历史 API 切换到使用哈希路由。如果你使用 React Router,你可以切换到
hashHistory
这个效果,但是 URL 会更长更冗长(例如,http://user.github.io/todomvc/#/todos/42?_k=yknaj
)。阅读更多关于 React Router 中不同历史实现的信息。 - 或者,您可以使用一个技巧,通过
index.html
使用特殊的重定向参数重定向到您的页面来教 GitHub Pages 处理 404 。在部署项目之前,您需要将404.html
带有重定向代码的build
文件添加到文件夹中,并且您需要将处理重定向参数的代码添加到index.html
. 您可以在本指南中找到有关此技术的详细说明。
<BrowserRouter basename="/calendar" />
<Link to="/today"/> // renders <a href="/calendar/today">
basename : string
所有位置的基本 URL。如果您的应用程序是从服务器上的子目录提供的,您需要将其设置为子目录。格式正确的基本名称应该有一个前导斜杠,但没有尾随斜杠。