Warm tip: This article is reproduced from serverfault.com, please click

reactjs-获取Electron生产窗口以使用loadURL加载路线?

(reactjs - Get Electron production window to load a route with loadURL?)

发布于 2020-11-28 06:40:51

我设法建立了我的react / electron应用程序,并使其在本地运行。但是,我的应用程序的“默认”路由为/app,因此,当我的应用程序在本地运行时,不会显示任何内容。这就是我所拥有的:

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")
);

我正在使用react-router来完成这项工作。这确实可以在本地工作,但不适用于生产环境。为了对此进行测试,我更改path="/app"path="/"并删除了exact它,并对其进行了构建,并按预期工作。但是,我确实希望它指向该特定/app路由,因为我希望其他不相关的窗口位于其他端点。我如何使构建正确识别这一点?我尝试过更改homepage: "./"homepage: "./app"in,package.json但没有任何改变。

编辑:我确实尝试将startURL更改为file://${path.join(__dirname, "../build/index.html#/app")}(添加#/app,如该答案所建议),但这也不起作用...

Questioner
IronWaffleMan
Viewed
0
IronWaffleMan 2020-11-30 13:02:25

事实证明,这个答案分为两个部分:第一个是错字。而不是#/app,添加#app是正确的(因此完整的字符串变为file://${path.join(__dirname, "../build/index.html#app")})。

另一个问题与react-router-dom和BrowserRouter表面上的问题有关它在生产中不起作用。所以我有这个:

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")
  );
}

HashRouter不开发工作,该代码因此有必要。