如何使用react router dom v4配置webpack dev服务器?

gpb*_*lio 25 reactjs webpack react-router webpack-dev-server react-router-v4

这是我的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')));
Run Code Online (Sandbox Code Playgroud)

工作正常,应用程序运行在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
);
Run Code Online (Sandbox Code Playgroud)

这是localhost的结果:3000/build.min.js 在localhost:3000 /约.我收到一个错误:无法获取/关于.不是我期待的,为什么这不会呈现?

关于

Upa*_*ana 57

我不认为它与webpack-config有任何关系.是一个使用react-router-4.0的基本github存储库.我创建了这个示例,没有任何与webpack配置中的react-router-4.0相关的具体更改.

如果尚未在webpack配置中添加'devServer':

devServer: {
    historyApiFallback: true,
  }
Run Code Online (Sandbox Code Playgroud)

在您的代码中有两个小建议,尝试使用'exact'和'about'的路径即ie

<Route exact path='/about' component={About}/>
Run Code Online (Sandbox Code Playgroud)

并为const添加括号ie,

const About = () => (<div> <h1>About</h1> </div>);
Run Code Online (Sandbox Code Playgroud)

希望,这解决了您的疑问.如果您需要任何其他信息,请与我们联系.