在 webpack 开发服务器上,有没有办法以编程方式从 browserHistory 切换到 hashHistory?

Is there a way to programatically switch to hashHistory from browserHistory when on a webpack dev server?

有没有办法在使用webpack-dev-server时自动从React Router中的browserHistory切换到hashHistory?如果页面刷新,我经常会收到 cannot GET/routename 错误。我可以通过手动切换到 hashHistory 来解决这个问题,但我想知道是否有一种好方法可以根据我是在开发还是生产中来回自动切换。

我的webpack.prod.config.js

const config = require('./webpack.config.js');
const webpack = require('webpack');

config.plugins.push(
  new webpack.DefinePlugin({
    "process.env": {
      "NODE_ENV": JSON.stringify("production")
    }
  })
);

config.plugins.push(
  new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false
    }
  })
);

module.exports = config;

我的路由器

render((
  <Router history={browserHistory}>
    {/** ###### HOME ROUTE ###### */}
    <Route path="/" component={Home} />
    <Route path="/company" component={Company} />
    <Route path="/help" component={Help} />
    <Route path="/features" component={Features} />
    <Route path="/signup" component={SignUp} />
    <Route path="/work" component={Work} />
    {/** ###### END HOME ROUTES ###### */}
  </Router>
), document.getElementById('root'));

您可以在设置历史记录之前检查 NODE_ENV 变量,类似这样

import { Router, Route, browserHistory,hashHistory IndexRoute } from 'react-router'

let history = process.env.NODE_ENV === "production" ? browserHistory : hashHistory;


render((
  <Router history={history}>
    {/** ###### HOME ROUTE ###### */}
    <Route path="/" component={Home} />
    <Route path="/company" component={Company} />
    <Route path="/help" component={Help} />
    <Route path="/features" component={Features} />
    <Route path="/signup" component={SignUp} />
    <Route path="/work" component={Work} />
    {/** ###### END HOME ROUTES ###### */}
  </Router>
), document.getElementById('root'));