目前主流項目方案 基本都是 采用SPA(單頁應用)架構去做的 那么url 基本是基于hash去做路由的. 這種不存在兼容性問題
為了url 清爽干凈的體驗 可以替換成 history model 3大框架都有自己的配置方式 .如果基于react-router 4 可以使用 官方提供的browserHistory去做。
實現(xiàn)一個完整 history mode 需要以下步驟:
假設我們部署項目名webapp
部署后的首頁 url為 http://www.xxx.com/webapp
1. 指定 basename
可以在 BrowserRouter 中進行指定
<BrowserRouter basename="/webapp" />
為了在 非react組件中也能使用router 進行導航 推薦將router 封裝一個服務,
BrowserRouter 和 router服務 選擇其中一種即可.
router服務 : RouterHelper.js
import createHistory from 'history/createBrowserHistory';
export const history = createHistory(
{
// 基鏈接
basename: "/webapp",
}
);
這樣在任意類中就可以引入router對象進行 路由導航,這種方式下basename指定需要在 createHistory中配置.
import {history} from "@common/class/RouterHelper";
在需要使用的類地方 可以導出使用。
一個完整的router服務的例子:
import {history} from "@common/class/RouterHelper";
const routes = [
{
path: "/account/user",
component: AccountManagerView,
meta : {title : "賬戶列表"},
},
{
path: "/account/userDetail",
component: AccountManagerDetailView,
meta : {title : "賬戶詳情"},
},];
import { Router ,Route, withRouter, Switch } from 'react-router-dom'
<Router history={history}>
<Switch>
{
routes.map((route,i)=> <Route key={i} exact {...route} />)
}
<Route render={() => <h1 className={''}>找不到此頁面</h1>} />
</Switch>
</Router>
ps : 注意使用router 服務方式 需要將history注入到 Router對象里面
2.nginx配置
將項目構建后 部署到nginx 靜態(tài)服務器上面

image.png
服務器上文件夾為 : webapp
#webapp
location /webapp {
alias /home/static/webapp/;
index index.html;
try_files $uri /webapp/index.html;
}
alias 指定資源訪問的目錄
try_files 當前uri 如果未找到則重新定位到 /webapp/index.html下;