I'm writing a react SPA that will be hosted by various clients in their own K8S clusters which I bundle as an image file. I have no idea up front what the hostname might be, nor what subpath they might choose to expose the app on (I'm assuming they'll use ingress to expose the app on a given subpath (HTTP routing) rather than using a port, but they might use both approaches.
The problem appears to be that the app requests resources (JS, CSS, etc.) from an absolute path (i.e. one that starts with a /
), rather than relative to the index file, therefore failing with a 404.
I've done some research, and it's possible to set a homepage
entry in the package.json
file, but that's only used when building and I don't have the required info when building, besides, this requires the full host, port, and subpath, which should be even less necessary than simply the subpath, and it's only available if one uses create-react-app. Another suggestion is to use the process.env.PUBLIC_URL
variable, but again, this is only available during building and that information isn't available.
Finally, I've also tried to configure the react router to deal with this problem, even though it needs to know the route during the build:
<Router basename={'/tui'}>
<Route path='/' component={Home} />
</Router>
But that, obviously, doesn't (and couldn't) work either. The main problem is js imports again.
Another suggested answer (below) is to use a script to rewrite URLs at application startup. This won't work for imports. It assumes that my app is all rolled up into a single file. This isn't the case with this app, where for some very good reasons, we can't roll it up into a single js file.
To be clear, my js imports are as relative as possible. So:
import ReactDOM from "react-dom/client";
import Page from "./Page.jsx";
The Page.jsx
file is defined relative to the current file (I have a flat src
directory), and the bundled libraries are imported as object references, not file references, under the assumption that the file has already been fetched in some way.
So, what to do? Is there a known way of solving this problem that allows me to run my react app on a subpath without specifying the subpath (or host or port) during the build?