I try to setup nested routes for my react app like this
/
-> Home Page/about
-> About Page/protected
I finally figured out the reason that webpack-dev-server couldn't serve nested routes.
As a single page application, when you visit /somepath
of your react app, it actually fallback to the /
and pass the pathname to react router. React router will navigate you to /somepath
by the using browser's history API.
webpack-dev-server, for some unknown reason, doesn't enable this "fallback to history API" behaviour by default.
So, we need to add historyApiFallback: true,
to the devServer
of webpack config.
Now, all top level routes, like /somepath
should work, but for nested routes, like /somepath/morepath
, it's not enough.
With default webpack-dev-server setting, the compiled html template will point to the bundled js like . Pay attention to the
src="main.js"
which assumes the main.js
is under the same path as the index.html
. The assumption is true for top level path /somepath
but for nested routes, /somepath/morepath
, this assumption will lead html file to access main.js
like /somepath/main.js
.
So, we end up with looking for a way to specify a certain place for html file when it's going to access the bundled js. And, it's the job of publicPath
. Adding publicPath: '/',
to the output block of webpack config. It will tell html to always access main.js
from /
folder and the compiled html will be . That's exactly what we're looking for.