如何配置Webpack开发服务器与React Router DOM v4?

37

这是我的Webpack配置代码:

const compiler = webpack({
  entry: ['whatwg-fetch', path.resolve(__dirname, 'js', 'app.js')], 
  module: {
    loaders: [
      {
        exclude: /node_modules/, 
        test: /\.js$/, 
        loader: 'babel',
      },
    ],
  },
  output: {filename: 'app.js', path: '/'}, 
});

const app = new WebpackDevServer(compiler, {
  contentBase: '/public/', 
  proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
  publicPath: '/js/',
  stats: {colors: true}, 
});

app.use('/', express.static(path.resolve(__dirname, 'public')));

运行良好,应用程序在 localhost:3000/index.html 上运行,但当我尝试实现 React Router dom v4 时,它无法正常工作。这是代码:

运行良好,应用程序在 localhost:3000/index.html 上运行,但当我尝试实现 React Router dom v4 时,它无法正常工作。这是代码:

const About = () => <div> <h1>About</h1> </div>

ReactDOM.render(
   <BrowserRouter>
      <div>
      <Route exact path='/' component={App}/>
      <Route  path='/about' component={About}/>
      </div>
    </BrowserRouter>,
  mountNode
);

这是在localhost:3000/的结果 build.min.js 而在localhost:3000/about。我收到一个错误:无法获取/about。这不是我期望的,为什么会无法渲染呢?

About


为什么要在你的路由组件周围添加额外的<div></div>?你应该在不同的路由之间放置<Switch></Switch>。https://reacttraining.com/react-router/web/api/Switch - Björn Böing
@Bjoern 我试过 Switch 但还是不行。我使用那些 divs 是因为 Router 只想要一个子元素。 - gpbaculio
4
嘿,你找到答案了吗?我也遇到了同样的问题... - Beckham_Vinoth
2个回答

101

我认为这与webpack配置无关。 这里是一个使用react-router-4.0的基本github存储库示例。我在没有对webpack配置进行任何与react-router-4.0相关的特定更改的情况下创建了此示例。

如果尚未添加,请在webpack配置中添加“devServer”:

devServer: {
    historyApiFallback: true,
  }

在您的代码中有两点小建议,尝试在关于页面的路径上使用'exact'。

<Route exact path='/about' component={About}/>

并且,对于const添加括号,例如:

const About = () => (<div> <h1>About</h1> </div>);
希望这能解决你的问题。如果你需要关于这个问题的其他信息,请告诉我。

1
我不知道historyApiFallback配置的历史,所以感谢您的分享。 - Kevin Østerkilde
我需要使用 npm start 重新启动我的应用程序。 - Pablo Cegarra
1
回退(fallback)特别是将404重定向到您的根目录或索引,让您模拟服务器端渲染或您可能在nginx、s3或其他应用部署中设置的回退。 - worc

2
在我的情况下,我必须移除代理配置,因为webpack服务器需要从 http://localhost:3001 获取响应。"原始答案"
// proxy: {
//   '/': 'http://localhost:3001',
// },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接