minishouyin/test/fix-electron-routes.js
2025-11-12 11:35:57 +08:00

326 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const fs = require('fs');
const path = require('path');
console.log('=== Electron路由修复工具 ===');
// 修复Layout.js中的菜单点击处理函数
function fixLayoutMenuClick() {
console.log('\n1. 修复Layout.js菜单点击处理函数...');
try {
const layoutPath = path.join(__dirname, 'src/renderer/components/Layout.js');
if (fs.existsSync(layoutPath)) {
let content = fs.readFileSync(layoutPath, 'utf8');
// 查找现有的handleMenuClick函数
const oldFunction = `function handleMenuClick({ key }) {
console.log('菜单点击:', key);
try {
navigate(key);
console.log('导航成功到:', key);
} catch (error) {
console.error('导航失败:', error);
// 直接使用window.location作为备选方案
window.location.href = key;
}
}`;
// 新的增强版函数
const newFunction = `function handleMenuClick({ key }) {
console.log('菜单点击:', key);
// 在Electron环境中使用更可靠的导航方式
try {
// 首先尝试使用React Router导航
navigate(key);
console.log('React Router导航成功到:', key);
} catch (routerError) {
console.error('React Router导航失败:', routerError);
// 如果React Router失败尝试使用window.location
try {
// 对于相对路径确保在Electron环境中正确处理
if (key.startsWith('/')) {
// 在Electron中我们需要使用hash模式或者特殊处理
const baseUrl = window.location.origin + window.location.pathname;
const newUrl = baseUrl.replace(/\\/[^\\/]*$/, '') + '#' + key;
window.location.hash = key;
} else {
window.location.href = key;
}
console.log('备用导航方式成功');
} catch (locationError) {
console.error('备用导航方式也失败了:', locationError);
// 最后的备选方案
window.location.reload();
}
}
}`;
// 替换函数
if (content.includes(oldFunction)) {
content = content.replace(oldFunction, newFunction);
fs.writeFileSync(layoutPath, content, 'utf8');
console.log(' ✅ Layout.js菜单点击处理函数已修复');
} else {
console.log(' ⚠️ 未找到预期的handleMenuClick函数可能已被修改');
}
} else {
console.log(' ❌ Layout.js文件不存在');
}
} catch (error) {
console.error(' ❌ 修复Layout.js失败:', error);
}
}
// 修复App.js中的路由配置
function fixAppRouting() {
console.log('\n2. 修复App.js路由配置...');
try {
const appPath = path.join(__dirname, 'src/renderer/App.js');
if (fs.existsSync(appPath)) {
let content = fs.readFileSync(appPath, 'utf8');
// 检查是否已经使用HashRouter
if (!content.includes('HashRouter')) {
// 替换BrowserRouter为HashRouter
content = content.replace(/BrowserRouter/g, 'HashRouter');
// 更新导入语句
if (content.includes("import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';")) {
content = content.replace(
"import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';",
"import { HashRouter as Router, Routes, Route } from 'react-router-dom';"
);
} else if (content.includes("import { BrowserRouter, Routes, Route } from 'react-router-dom';")) {
content = content.replace(
"import { BrowserRouter, Routes, Route } from 'react-router-dom';",
"import { HashRouter, Routes, Route } from 'react-router-dom';"
);
}
fs.writeFileSync(appPath, content, 'utf8');
console.log(' ✅ App.js路由配置已修复使用HashRouter');
} else {
console.log(' ✅ App.js已使用HashRouter无需修改');
}
} else {
console.log(' ❌ App.js文件不存在');
}
} catch (error) {
console.error(' ❌ 修复App.js路由配置失败:', error);
}
}
// 创建Electron环境下的路由助手
function createRouteHelper() {
console.log('\n3. 创建Electron路由助手...');
try {
const helperPath = path.join(__dirname, 'src/renderer/utils/electron-router.js');
// 确保utils目录存在
const utilsDir = path.dirname(helperPath);
if (!fs.existsSync(utilsDir)) {
fs.mkdirSync(utilsDir, { recursive: true });
}
const helperContent = `/**
* Electron环境路由助手
* 提供在Electron桌面应用中更可靠的路由导航功能
*/
/**
* 在Electron环境中安全地导航到指定路径
* @param {string} path - 目标路径
* @param {object} navigate - React Router的navigate函数
*/
export function electronNavigate(path, navigate) {
console.log('Electron导航到:', path);
try {
// 首先尝试使用React Router
if (navigate && typeof navigate === 'function') {
navigate(path);
console.log('React Router导航成功');
return;
}
} catch (routerError) {
console.warn('React Router导航失败:', routerError);
}
// 备用方案使用window.location
try {
if (path.startsWith('/')) {
// 对于绝对路径在Electron中使用hash模式
window.location.hash = path;
} else {
// 相对路径直接跳转
window.location.href = path;
}
console.log('备用导航方式成功');
} catch (locationError) {
console.error('备用导航方式失败:', locationError);
// 最后方案:刷新页面
window.location.reload();
}
}
/**
* 获取当前路由路径
* @returns {string} 当前路径
*/
export function getCurrentRoute() {
// 在Electron中我们可能需要从hash中获取路径
if (window.location.hash) {
return window.location.hash.substring(1); // 移除开头的#
}
return window.location.pathname;
}
/**
* 初始化Electron路由环境
*/
export function initElectronRouter() {
console.log('初始化Electron路由环境');
// 确保基础href设置正确
let base = document.querySelector('base');
if (!base) {
base = document.createElement('base');
base.href = './';
document.head.appendChild(base);
}
// 监听路由变化
window.addEventListener('hashchange', () => {
console.log('路由变化到:', window.location.hash);
});
}
export default {
electronNavigate,
getCurrentRoute,
initElectronRouter
};`;
fs.writeFileSync(helperPath, helperContent, 'utf8');
console.log(' ✅ Electron路由助手已创建');
} catch (error) {
console.error(' ❌ 创建Electron路由助手失败:', error);
}
}
// 更新Layout.js使用新的路由助手
function updateLayoutWithHelper() {
console.log('\n4. 更新Layout.js使用路由助手...');
try {
const layoutPath = path.join(__dirname, 'src/renderer/components/Layout.js');
if (fs.existsSync(layoutPath)) {
let content = fs.readFileSync(layoutPath, 'utf8');
// 添加导入语句
const importStatement = "import { electronNavigate } from '../utils/electron-router';";
if (!content.includes(importStatement)) {
// 在其他导入语句之后添加
content = content.replace(
"import { useNavigate, useLocation } from 'react-router-dom';",
"import { useNavigate, useLocation } from 'react-router-dom';\nimport { electronNavigate } from '../utils/electron-router';"
);
}
// 更新handleMenuClick函数
const oldFunction = `function handleMenuClick({ key }) {
console.log('菜单点击:', key);
// 在Electron环境中使用更可靠的导航方式
try {
// 首先尝试使用React Router导航
navigate(key);
console.log('React Router导航成功到:', key);
} catch (routerError) {
console.error('React Router导航失败:', routerError);
// 如果React Router失败尝试使用window.location
try {
// 对于相对路径确保在Electron环境中正确处理
if (key.startsWith('/')) {
// 在Electron中我们需要使用hash模式或者特殊处理
const baseUrl = window.location.origin + window.location.pathname;
const newUrl = baseUrl.replace(/\\/[^\\/]*$/, '') + '#' + key;
window.location.hash = key;
} else {
window.location.href = key;
}
console.log('备用导航方式成功');
} catch (locationError) {
console.error('备用导航方式也失败了:', locationError);
// 最后的备选方案
window.location.reload();
}
}
}`;
const newFunction = `function handleMenuClick({ key }) {
console.log('菜单点击:', key);
// 使用Electron路由助手进行导航
electronNavigate(key, navigate);
}`;
if (content.includes(oldFunction)) {
content = content.replace(oldFunction, newFunction);
fs.writeFileSync(layoutPath, content, 'utf8');
console.log(' ✅ Layout.js已更新使用路由助手');
} else {
console.log(' ⚠️ 未找到预期的handleMenuClick函数可能已被修改');
}
} else {
console.log(' ❌ Layout.js文件不存在');
}
} catch (error) {
console.error(' ❌ 更新Layout.js失败:', error);
}
}
// 更新package.json添加构建脚本
function updatePackageJson() {
console.log('\n5. 更新package.json...');
try {
const packagePath = path.join(__dirname, 'package.json');
if (fs.existsSync(packagePath)) {
const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
// 添加Electron专用的构建脚本
if (!packageData.scripts['build-electron']) {
packageData.scripts['build-electron'] = 'npm run build-renderer && npm run build-main';
}
// 确保homepage设置正确
packageData.homepage = './';
fs.writeFileSync(packagePath, JSON.stringify(packageData, null, 2), 'utf8');
console.log(' ✅ package.json已更新');
} else {
console.log(' ❌ package.json文件不存在');
}
} catch (error) {
console.error(' ❌ 更新package.json失败:', error);
}
}
// 主函数
function main() {
console.log('开始修复Electron环境中的路由问题...\n');
fixLayoutMenuClick();
fixAppRouting();
createRouteHelper();
updateLayoutWithHelper();
updatePackageJson();
console.log('\n=== 路由修复完成 ===');
console.log('请重新构建并启动应用以使更改生效:');
console.log(' 1. npm run build');
console.log(' 2. npm start');
}
// 执行修复
main();