常见问题 FAQ
安装和环境
Q1: Electron 安装失败,提示 "Electron failed to install correctly"
问题描述:
Electron failed to install correctly, please delete node_modules/electron and try installing again原因分析:
- 网络问题导致 Electron 二进制文件下载失败
- 国内访问 GitHub Releases 速度慢或被屏蔽
- 缓存文件损坏
解决方案:
方案 1:使用项目提供的修复命令
pnpm fix:electron-deps方案 2:配置国内镜像
# Windows PowerShell
$env:ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"
pnpm install
# Windows CMD
set ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
pnpm install
# Mac/Linux
export ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
pnpm install方案 3:手动下载安装
# 1. 删除 node_modules/electron
rm -rf node_modules/electron
# 2. 清除 pnpm 缓存
pnpm store prune
# 3. 重新安装
pnpm install方案 4:使用代理
# 如果有 HTTP 代理
export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890
pnpm installQ2: Node.js 版本不符合要求
问题描述:
ERROR: The engine "node" is incompatible with this module. Expected version ">=18.0.0". Got "16.14.0"解决方案:
使用 nvm 管理 Node.js 版本:
# Windows - 使用 nvm-windows
# 下载:https://github.com/coreybutler/nvm-windows/releases
# 安装 Node.js 18
nvm install 18
# 切换到 Node.js 18
nvm use 18
# Mac/Linux - 使用 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 安装并使用 Node.js 18
nvm install 18
nvm use 18或直接下载安装:
- 官网:https://nodejs.org/
- 选择 LTS 版本(推荐 18.x 或 20.x)
Q3: pnpm 命令不存在
问题描述:
pnpm: command not found解决方案:
# 使用 npm 全局安装 pnpm
npm install -g pnpm
# 或使用 npx(临时使用)
npx pnpm install
# 验证安装
pnpm --version开发调试
Q4: 开发模式启动失败,窗口无法打开
问题描述:
- 执行
pnpm dev后,命令行没有错误但窗口不出现 - 或提示 "Error: Electron failed to load"
排查步骤:
1. 检查端口占用
# Windows
netstat -ano | findstr :5173
# Mac/Linux
lsof -i :5173
# 如果端口被占用,修改 Vite 配置
# renderer/vite.config.js
export default defineConfig({
server: {
port: 5174 // 改为其他端口
}
});2. 检查防火墙
- Windows:允许 Node.js 和 Electron 通过防火墙
- Mac:系统偏好设置 -> 安全性与隐私 -> 防火墙
3. 查看详细日志
# 开启详细日志
DEBUG=* pnpm dev
# 或分别启动查看具体错误
pnpm dev:renderer # 先启动渲染进程
pnpm dev:main # 再启动主进程4. 清除缓存重试
# 清除 node_modules
rm -rf node_modules
rm -rf packages/*/node_modules
# 清除 pnpm 缓存
pnpm store prune
# 重新安装
pnpm installQ5: 页面加载空白,控制台无错误
可能原因:
- Vue Router 路由配置错误
- 静态资源路径错误
- CSP(内容安全策略)限制
解决方案:
1. 检查路由配置
// renderer/src/router/index.js
const router = createRouter({
history: createWebHashHistory(), // 使用 hash 模式
routes: [
{
path: '/',
component: () => import('../pages/Home.vue'),
},
],
});2. 检查 Vite 配置的 base
// renderer/vite.config.js
export default defineConfig({
base: './', // 使用相对路径
build: {
outDir: 'dist',
},
});3. 检查 CSP 配置
<!-- renderer/index.html -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob:;"
/>4. 打开开发者工具调试
// 在主进程中
mainWindow.webContents.openDevTools();
// 或使用快捷键
// Ctrl+Alt+D(已配置)Q6: 热更新(HMR)不工作
问题描述:
- 修改 Vue 文件后,页面不自动刷新
- 需要手动刷新才能看到更改
解决方案:
1. 检查 Vite HMR 配置
// renderer/vite.config.js
export default defineConfig({
server: {
hmr: {
protocol: 'ws',
host: 'localhost',
},
},
});2. 确保使用开发模式加载
// main/src/core/window.js
const isDev = process.env.NODE_ENV === 'development';
if (isDev) {
win.loadURL('http://localhost:5173'); // HMR 工作
} else {
win.loadFile('renderer/dist/index.html');
}3. 检查防火墙是否阻止 WebSocket 连接
打包部署
Q7: 打包后应用无法启动
问题描述:
- 双击 exe 文件后,没有任何反应
- 或闪退,没有错误提示
调试方法:
1. 使用命令行启动,查看错误信息
cd dist/win-unpacked
./vue3-simple-electron.exe
# 或
start vue3-simple-electron.exe2. 检查日志文件
# Windows
%APPDATA%/vue3-simple-electron/logs/main.log
# Mac
~/Library/Application Support/vue3-simple-electron/logs/main.log
# Linux
~/.config/vue3-simple-electron/logs/main.log3. 常见原因和解决方案:
原因 1:资源文件路径错误
// ❌ 错误:使用绝对路径
const iconPath = 'D:/project/resources/icon.ico';
// ✅ 正确:使用相对路径
const iconPath = path.join(__dirname, '../resources/icon.ico');
// ✅ 或使用 process.resourcesPath
const iconPath = path.join(process.resourcesPath, 'icon.ico');原因 2:依赖未正确打包
// electron-builder.config.js
module.exports = {
files: ['packages/main/dist/**/*', 'packages/renderer/dist/**/*', '!node_modules/**/*'],
extraResources: [
{
from: 'resources',
to: 'resources',
},
],
asarUnpack: [
'**/*.node', // 原生模块
'resources/**/*',
],
};原因 3:配置文件缺失
- 确保
resources/config/config.ini被正确打包 - 检查
electron-builder.config.js中的extraResources配置
Q8: 打包后文件体积过大
问题描述:
- 安装包超过 200MB
- 解压后文件夹超过 500MB
优化方案:
1. 排除不必要的依赖
// electron-builder.config.js
module.exports = {
files: [
'!**/*.map', // 排除 source map
'!**/*.ts', // 排除 TypeScript 源文件
'!**/README.md', // 排除文档
'!**/test/**', // 排除测试文件
'!**/docs/**', // 排除文档目录
],
};2. 使用 asar 压缩
module.exports = {
asar: true, // 启用 asar 打包
asarUnpack: [
'**/*.node', // 原生模块不能被 asar 打包
],
};3. 压缩安装包
module.exports = {
compression: 'maximum', // 最大压缩
nsis: {
oneClick: false,
perMachine: false,
allowToChangeInstallationDirectory: true,
},
};4. 分析依赖大小
# 安装分析工具
pnpm add -D rollup-plugin-visualizer
# 构建时生成分析报告
pnpm build
# 查看 stats.html5. 删除开发依赖
// package.json
{
"devDependencies": {
// 开发依赖不会被打包
},
"dependencies": {
// 只保留生产依赖
}
}Q9: 打包失败,提示 "Cannot find module"
问题描述:
Error: Cannot find module '@/utils/logger'原因:
- Webpack/Vite 别名在打包后不生效
- 动态 require 路径解析失败
解决方案:
1. 避免使用别名(主进程)
// ❌ 不推荐:使用别名
const logger = require('@/utils/logger');
// ✅ 推荐:使用相对路径
const logger = require('../utils/logger');2. 避免动态 require
// ❌ 不推荐:动态路径
const moduleName = 'logger';
const logger = require(`../utils/${moduleName}`);
// ✅ 推荐:静态路径
const logger = require('../utils/logger');3. 配置 Webpack externals
// webpack.config.js(如果使用)
module.exports = {
externals: {
electron: 'commonjs electron',
fs: 'commonjs fs',
path: 'commonjs path',
},
};功能使用
Q10: 悬浮球不显示
问题描述:
- 点击托盘菜单"显示悬浮球"没有反应
- 或使用快捷键
Ctrl+Alt+H无效
排查步骤:
1. 检查悬浮球服务是否初始化
// main/src/apps/app-initializer.js
FloatingBallService.initialize(mainWindow);2. 检查悬浮球 HTML 文件
# 确保文件存在
packages/renderer/ball.html
# 检查是否被正确打包
dist/win-unpacked/resources/app.asar(或 app 目录)3. 查看控制台错误
// 在悬浮球服务中添加日志
FloatingBallService.create = function () {
try {
logger.info('创建悬浮球窗口');
// ...
} catch (error) {
logger.error('创建悬浮球失败:', error);
}
};4. 检查窗口是否被隐藏
// 尝试强制显示
const floatingWindow = FloatingBallService.floatingWindow;
if (floatingWindow) {
floatingWindow.show();
floatingWindow.focus();
}Q11: 插件无法加载
问题描述:
- 上传插件后显示"加载失败"
- 插件列表为空
解决方案:
1. 检查插件格式
my-plugin.zip
├── manifest.json ✅ 必须包含
├── index.js ✅ 入口文件
├── package.json ⚠️ 可选
└── assets/ ⚠️ 可选2. 验证 manifest.json
{
"id": "my-plugin", // ✅ 必填,唯一标识
"name": "我的插件", // ✅ 必填
"version": "1.0.0", // ✅ 必填
"main": "index.js", // ✅ 必填,入口文件
"description": "插件描述", // ⚠️ 可选
"author": "作者", // ⚠️ 可选
"permissions": [] // ⚠️ 可选
}3. 检查入口文件
// index.js
module.exports = {
// ✅ 必须导出 initialize 方法
async initialize(context) {
console.log('插件初始化', context);
},
// ⚠️ 可选的生命周期方法
async start() {
console.log('插件启动');
},
async stop() {
console.log('插件停止');
},
};4. 查看插件日志
// 插件目录
%APPDATA%/vue3-simple-electron/plugins/
// 查看插件日志
%APPDATA%/vue3-simple-electron/logs/plugin-{plugin-id}.logQ12: 自动更新不工作
问题描述:
- 点击"检查更新"没有反应
- 或始终提示"已是最新版本"
配置检查:
1. 确认配置文件
# resources/config/config.ini
[Update]
autoCheckUpdate=true
updateUrl=https://your-server.com/update/latest.json2. 更新服务器配置
// latest.json
{
"version": "1.1.0",
"releaseDate": "2025-01-15",
"downloadUrl": "https://your-server.com/download/v1.1.0.zip",
"releaseNotes": "更新说明..."
}3. 检查更新处理器
// 确保更新处理器已注册
const updateHandler = new UpdateHandler(mainWindow);
// 手动触发更新检查
updateHandler.checkForUpdates();4. 查看网络请求
// 添加请求日志
axios
.get(updateUrl)
.then((response) => {
logger.info('更新检查响应:', response.data);
})
.catch((error) => {
logger.error('更新检查失败:', error);
});Q13: 本地服务器代理不生效
问题描述:
- 配置了 proxy-rules.yaml 但代理不工作
- API 请求返回 404
排查步骤:
1. 检查配置文件格式
# resources/config/proxy-rules.yaml
proxies:
- path: /api # ✅ 正确
target: https://api.example.com
changeOrigin: true
# ❌ 错误的格式
- path: '/api' # 不要加引号(YAML 中可省略)
target: https://api.example.com2. 检查本地服务器是否启动
# config.ini
[Server]
enableLocalServer=true # 确保为 true
localServerPort=80803. 查看代理日志
// 在本地服务器中添加日志
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
});4. 测试代理规则
// 在渲染进程控制台测试
fetch('/api/test')
.then((res) => res.json())
.then((data) => console.log('Success:', data))
.catch((err) => console.error('Error:', err));性能问题
Q14: 应用启动缓慢
问题描述:
- 双击图标后,等待 10 秒以上才显示窗口
- 启动时 CPU 占用很高
优化方案:
1. 使用异步初始化
async function initializeApp() {
// ✅ 先创建窗口,立即显示
const mainWindow = createWindow();
// ✅ 并行初始化服务
await Promise.all([MachineService.initialize(), PluginService.initialize()]);
// ❌ 避免阻塞窗口显示
// await heavyOperation();
}2. 延迟加载非关键模块
// ✅ 窗口显示后再加载
mainWindow.webContents.once('did-finish-load', () => {
// 加载非关键功能
loadPlugins();
checkUpdates();
});3. 优化日志初始化
// ✅ 异步初始化日志清理
LoggerClean.getInstance()
.initialize()
.catch((err) => {
console.error('日志初始化失败:', err);
});4. 减少同步 I/O 操作
// ❌ 避免:同步读取文件
const config = fs.readFileSync('config.ini', 'utf-8');
// ✅ 推荐:异步读取
const config = await fs.promises.readFile('config.ini', 'utf-8');Q15: 内存占用过高
问题描述:
- 应用占用内存超过 500MB
- 长时间运行后内存持续增长
排查方法:
1. 使用性能分析工具
// 在开发者工具中
// Performance -> Memory -> Take heap snapshot2. 检查定时器泄漏
// ✅ 确保清理定时器
class MyService {
start() {
this.timer = setInterval(() => {
this.doWork();
}, 1000);
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
}3. 检查事件监听器泄漏
// ✅ 清理事件监听
app.on('before-quit', () => {
ipcMain.removeAllListeners();
mainWindow.webContents.removeAllListeners();
});4. 清理缓存
// 定期清理缓存
setInterval(
() => {
CacheService.clearExpired();
},
60 * 60 * 1000,
); // 每小时平台兼容
Q16: Windows 7 无法运行
问题描述:
- Windows 7 上双击无反应
- 或提示"不是有效的 Win32 应用程序"
解决方案:
当前项目使用 Electron 22,支持 Windows 7/8/10/11。
确认版本:
// package.json
{
"devDependencies": {
"electron": "^22.0.0" // ✅ 支持 Win7
// "electron": "^28.0.0" // ❌ 不支持 Win7
}
}其他检查:
- 确保 .NET Framework 4.5+ 已安装
- 确保 Visual C++ Redistributable 已安装
- 更新 Windows 7 到最新 Service Pack
其他问题
Q17: 如何调试主进程?
方法 1:使用 console.log
console.log('调试信息', data);
console.error('错误信息', error);方法 2:使用 logger
logger.info('信息');
logger.error('错误', error);
// 查看日志文件
// %APPDATA%/vue3-simple-electron/logs/main.log方法 3:使用 VS Code 调试
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": ["."],
"outputCapture": "std"
}
]
}方法 4:使用 Chrome DevTools
# 启动时开启远程调试
electron --inspect=5858 .
# 在 Chrome 中访问
chrome://inspectQ18: 获取更多帮助
官方资源:
项目资源:
- 📧 Email: lmxzqq@gmail.com
- 🐛 GitHub Issues
- 📖 在线文档
社区资源:
问题反馈
如果以上 FAQ 未能解决您的问题,请通过以下方式反馈:
GitHub Issues:https://github.com/your-repo/issues
- 描述问题现象
- 提供错误日志
- 说明操作系统和版本
- 附上复现步骤
Email:lmxzqq@gmail.com
- 详细描述问题
- 附上日志文件
- 说明期望的行为
提交 PR
- 如果您找到了解决方案
- 欢迎提交 Pull Request
- 帮助改进项目