Friday, April 13, 2018

BrowserRouter not working with webpack build directory

Leave a Comment

I noticed today that the BrowserRouter for react-router v4 does not work when I am using the npm package "serve" to host my application. It works fine though when I am doing development via webpack-dev-server if my webpack.config contains this property under module rules.

devServer: {     contentBase: path.join(__dirname, 'dist'),     historyApiFallback: true, <---- this is key to have for the router to work     compress: true,     port: 8080   } 

Now if I switch from BrowserRouter to HashRouter, both the dev server and when I serve the dist directory both work fine!

Can anybody please show me how they are hosting their application with BrowserRouter via build output from webpack and also possibly explain to me why BrowserRouter fails to work from a bundle being hosted with the serve npm package? I amassuming it has something to do with the historyApiFallback.

1 Answers

Answers 1

Ok, I will give it a try - my second answer on StackOverflow!

The difficulty with this question is that you do not share enough information to get a clear view of the problem (at least package.json, some code). Which fortunately leaves a lot of freedom in giving an answer :-)

In the fast-moving world of JavaScript I would suggest to search for the latest information you can get. Don't sweat a tear on yesterdays configuration - if it does not run. My entry point is https://reacttraining.com/react-router/web/guides/quick-start. The tutorial describes how to implement the react-router.

So far so good, build the productive bundle with yarn build, and the output suggests

The build folder is ready to be deployed. You may serve it with a static server:    yarn global add serve   serve -s build 

Here I had a small hold-up as the serve module was not accessible from the console. This was quickly resolved by the accepted answer and comments in Yarn global command not working.

Now serve -s build does the job.

Conclusion: You may have an undefined state in your application, grep -r "devServer:" . does yield nothing on my side. I suppose using yarn and npm at the same time could be responsible for this (to be verified ...).

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment