I've managed to build my react/electron app and have it run locally. However, the 'default' route for my app is /app
, so when my app runs locally, nothing shows up. This is what I have:
public/main.js:
function createWindow() {
mainWindow = new BrowserWindow({
width: 400,
height: 400,
show: true,
frame: false,
transparent: true,
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
},
});
const startURL = isDev
? "http://localhost:3000/app"
: `file://${path.join(__dirname, "../build/index.html")}`;
mainWindow.loadURL(startURL);
mainWindow.once("ready-to-show", () => {
// mainWindow.show()
mainWindow.setSize();
});
mainWindow.on("closed", () => {
mainWindow = null;
});
}
app.on("ready", createWindow);
src/index.js:
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Route path="/app" exact component={App} />
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
I'm using react-router to make this work. This does work locally, just not in production. To test this, I changed path="/app"
to path="/"
and removed exact
, built it, and it worked as expected. However, I do want this to point at that particular /app
route, since I want other unrelated windows to be at other endpoints. How do I get the build to recognise this properly? I've tried changing homepage: "./"
to homepage: "./app"
in package.json
but that didn't change anything.
EDIT: I did try changing the startURL to file://${path.join(__dirname, "../build/index.html#/app")}
(adding the #/app
, as suggested by this answer) but that didn't work either...
Turns out there's two parts to this answer; the first one was a typo. Instead of #/app
, adding #app
is correct (so the full string becomes file://${path.join(__dirname, "../build/index.html#app")}
).
The other issue is related to react-router-dom and the BrowserRouter
apparently; it doesn't work in production. So instead I have this:
if (!process.env.NODE_ENV || process.env.NODE_ENV === "development") {
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Route path="/app" exact component={App} />
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
} else {
ReactDOM.render(
<React.StrictMode>
<HashRouter>
<Route path="/app" exact component={App} />
</HashRouter>
</React.StrictMode>,
document.getElementById("root")
);
}
The HashRouter
doesn't work in dev, hence the necessity of this code.