[英]How to route in electron react app during production
I am using electron 6.10.0 and using React.js.我正在使用 electron 6.10.0 并使用 React.js。
In my app, there is an add task option in menu, which creates a new window.在我的应用程序中,菜单中有一个添加任务选项,它创建了一个新的 window。
Everything works fine during development, but during production this line causes problem.在开发过程中一切正常,但在生产过程中,这条线会导致问题。
addWindow.loadURL(isDev? 'http://localhost:3000/add': `file://${path.join(__dirname, '../build/index.html')}`);
It loads index.html, through which it loads index.js and which renders router.js.它加载 index.html,通过它加载 index.js 并渲染 router.js。 This is the code in Router.js.这是 Router.js 中的代码。
<HashRouter>
<Switch>
<Route exact path="/" component={App} />
<Route exact path="/add" component={addWindow} />
</Switch>
</HashRouter>
Mainwindow works fine because the hash is ' / ' but for add window the hash doesn't change and it loads the mainwindow content again in addwindow.主窗口工作正常,因为 hash 是“/”,但添加 window hash 不会改变,它会在 addwindow 中再次加载主窗口内容。
How to use the route/Router during production, or is there any other way around.如何在生产过程中使用路由/路由器,或者有其他方法。
Thanks in advance.提前致谢。
Ok, I solved it by adding #/add at the end of the link, like this:好的,我通过在链接末尾添加 #/add 来解决它,如下所示:
addWindow.loadURL(isDev ?
'http://localhost:3000/add' :
`file://${path.join(__dirname, '../build/index.html#/add')}`);
In my case, I had a problem with a hash fragment in a path that is encoded as /build/index.html%23add
, and that file/url doesn't exist.就我而言,我在编码为/build/index.html%23add
的路径中的 hash 片段存在问题,并且该文件/网址不存在。
I added hash
property to url format and all works fine.我将hash
属性添加到 url 格式,一切正常。
const path = require('path')
const url = require('url')
url.format({
pathname: path.join(__dirname, 'index.html'),
hash: '/add',
protocol: 'file:',
slashes: true
})
I had the same issue while trying to build electron/react app.我在尝试构建电子/反应应用程序时遇到了同样的问题。 url.format() works like a charm but unfortunately it's deprecated since node v11. url.format() 就像一个魅力,但不幸的是它自节点 v11 以来已被弃用。 I made a simple helper function that uses new URL class syntax.我做了一个简单的助手 function ,它使用新的 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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.