Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

reactjs - How to configure webpack dev server with react router dom v4?

This is the code of my webpack configuration:

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')));

Works fine, the app runs on localhost:3000/index.html but when I try to implement React Router dom v4. It doesn't work. This is the code:

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

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

This is the result on localhost:3000/ build.min.js And on localhost:3000/about. I get an error: Cannot GET /about . Not what I'm expecting, why would this not render?

About

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I do not think it has anything to do with webpack-config. Here is a basic github repository using react-router-4.0. I have created this example without any specific changes related to react-router-4.0 in webpack config.

Add 'devServer' in your webpack config if not already:

devServer: {
    historyApiFallback: true,
  }

Two small suggestions in your code, try using 'exact' with the path for 'about' i.e.

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

and, add parenthesis for const about i.e.,

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

Hope, this solves your query. Let me know if you require any other information on this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...