React使用browserHistory路由,常见服务器配置汇总

React新版本中使用browserHistory的方法:

import React, { Component, Suspense, lazy } from 'react';
import { Route, HashRouter, Switch, Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';

const Home = lazy(() => import('../page/home/Home'));
const Login = lazy(() => import('../page/user/Login'));
const NotFound = lazy(() => import('../page/not-found/NotFound'));

const browserHistory = createBrowserHistory();

export default function App(props) {
    return (
        <>
            <Router history={browserHistory}>
            <Switch>
                <Route exact path="/" component={Home} />
                <Route path="/login" component={Login} />
                <Route path="*" component={NotFound} />
            </Switch>
             </Suspense>
            </Router>
        </>
    )
}

browserHistory与其他两种路由方式(hashHistory、createMemoryHistory)相比,多一步要配置服务端,原理不多说,直接盘点常见服务器下的配置。

Nginx

*.conf文件

server {
  ...
  location / {
    try_files $uri /index.html
  }
  ...
}

Express

index.js文件

const express = require('express');
const path = require('path');
const port = process.env.PORT || 9999;
const app = express();

app.use(express.static(__dirname + '/public'));

app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
});

app.listen(port);
console.log("Server started on port: " + port);

Apache

.htaccess文件

RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

webpack-dev-server

webpack.config.js文件

devServer选项协助wepack-dev-server支持h5 history api的路由,非常关键。

module.exports = {
    entry: "./src/index.js",
    output: {
        path: path.join(__dirname, 'build'),
        publicPath: '/',
        filename: `${STATIC_PATH}/js/[hash].[name].js`,
    },
    devServer: {
        historyApiFallback:{
            index:'/index.html'
        },
    },
    ...
};

参考资料

https://www.jianshu.com/p/42001f172d90

https://echizen.github.io/tech/2016/07-05-webpack-dev-server-react-router-config