How to configure webpack dev server with react router dom v4?
Solution 1
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.
Solution 2
In my case I had to remove proxy config, because the webpack server wanted a response from http://localhost:3001.
// proxy: {
// '/': 'http://localhost:3001',
// },
gpbaculio
I have a degree in Bachelor of Science Major in Information Technology with concentration in Web Development. I further developed my frontend and backend skills on freecodecamp . I have used in my projects backend and frontend technologies such as Typescript, React, React Native, Redux, Apollo, Relay Modern, GraphQL, Mongoose, Express, etc.
Updated on October 17, 2020Comments
-
gpbaculio over 3 years
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/ And on localhost:3000/about. I get an error: Cannot GET /about . Not what I'm expecting, why would this not render?
About
-
Kevin Østerkilde over 6 yearsI didn't know about the historyApiFallback config, so thanks for sharing.
-
Pablo Cegarra almost 6 yearsI needed to restart my app with npm start
-
worc over 5 yearsfallback specifically redirects 404s back to your root or index, letting you mimic server-side rendering or fallbacks you might have setup in nginx or s3 or however else your app deploys.