如何在生产过程中在电子反应应用程序中路由

How to route in electron react app during production

我正在使用 electron 6.10.0 并使用 React.js。

在我的应用程序中,菜单中有一个添加任务选项,它会创建一个新的 window。

在开发过程中一切正常,但在生产过程中这条线会出现问题。

addWindow.loadURL(isDev ? 'http://localhost:3000/add' : `file://${path.join(__dirname, '../build/index.html')}`);

它加载 index.html,通过它加载 index.js 并呈现 router.js。这是 Router.js.

中的代码
<HashRouter>
    <Switch>
      <Route exact path="/" component={App} />
      <Route exact path="/add" component={addWindow} />
    </Switch>
  </HashRouter>

Mainwindow 工作正常,因为散列是 '/' 但对于 add window 散列没有改变,它在 add[= 中再次加载 mainwindow 内容34=].

如何在制作过程中使用route/Router,或者有没有其他方法。

提前致谢。

好的,我通过在 link 的末尾添加 #/add 来解决它,就像这样:

addWindow.loadURL(isDev ? 
'http://localhost:3000/add' :
`file://${path.join(__dirname, '../build/index.html#/add')}`);

在我的例子中,我遇到了编码为 /build/index.html%23add 的路径中的散列片段问题,并且 file/url 不存在。

我将 hash 属性 添加到 url 格式,一切正常。

const path = require('path')
const url = require('url')

url.format({
    pathname: path.join(__dirname, 'index.html'),
    hash: '/add',
    protocol: 'file:',
    slashes: true
})

我在尝试构建 electron/react 应用程序时遇到了同样的问题。 url.format() 就像一个魅力,但不幸的是,自节点 v11 以来它已被弃用。我制作了一个使用新 URL class 语法的简单辅助函数。

const isDev = require('electron-is-dev');
const { URL } = require('url');

// Define React App dev and prod base paths
const devBasePath = 'http://localhost:3000/';
const prodBasePath = `file://${__dirname}/build/index.html`;

const constructAppPath = (hashRoute = '') => {
  const basePath = isDev ? devBasePath : prodBasePath;

  const appPath = new URL(basePath);

  // Add hash route to base url if provided
  if (hashRoute) appPath.hash = hashRoute;

  // Return the constructed url
  return appPath.href;
};

console.log('initial path', constructAppPath());
console.log('hash path', constructAppPath('/example/path'));