Support Webpack HMR with non-root base URLs #488
Description
Since Webpack dev middleware is a dev-time-only (not production) feature, this will only affect people whose development environment is set up to host their site at a non-root URL (e.g., http://localhost:port/somedir). This is a very unusual configuration, and in fact is quite hard to set up even on its own as you most likely need some external reverse proxy (e.g., nginx) on your development machine to make that happen. Very few people will do this.
Now, for people who do that, HMR won't work out-of-the-box right now, because the Webpack configuration doesn't know what directory you're hosting your app inside.
The PathBase information doesn't exist until runtime inside the context of a specific HTTP request where PathBase
has been populated by UsePathBaseMiddleware. This is tricky for HMR, because the HMR's endpoint (e.g., /__webpack_hmr
) is compiled into your .js
bundle at build time.
The best solution I have in mind is:
- Instruct developers that, if they plan to deploy to a non-root URL, then they have to configure
publicPath
values in their Webpack config accordingly. ThepublicPath
values must truly reflect the URLs that browsers need to make requests to (this is the case even for regular production deployments; it's not specific to HMR).- At dev time, having correctly-prefixed
publicPath
values (e.g.,/vdir/dist/
) will automatically configure the client-side code to fetch HMR updates (e.g., blah123123.hot-update.json) from under that URL root - However, on its own, it would break the HMR proxying, because the current .NET-side proxying code would then start listening for requests under
/vdir/vdir/dist
.
- At dev time, having correctly-prefixed
- To fix that latter problem, add a further option on WebpackDevMiddlewareOptions:
BaseUrl
. Amend the proxying code to automatically strip off that prefix from thepublicPath
values that it adds proxy listeners for. - Also, the .NET-side HMR code can add the configured
BaseUrl
value as a prefix onto thehotModuleReplacementEndpointUrl
that it passes to the Node code. Then the client will correctly attempt to connect to (e.g.)/vdir/__webpack_hmr
instead of just/__webpack_hmr
.
So, it's not going to make things automatic for developers, but:
- It's inevitable that they have to tweak
publicPath
values in Webpack config manually, because that's a compile-time item, and must actually reflect real URLs so that things like images/CSS/etc can actually be loaded from their true complete URLs in production - It's (almost) inevitable that some specific
BaseUrl
must also be configured, because otherwise there wouldn't necessarily be a single specific one we can use when controlling the HMR endpoint location. The only way to avoid this would be if we delayed WebpackDevMiddleware compilation until requests actually started, and then obtained thePathBase
from the incoming requests.