Electron整合wiki.js后打包生成的exe运行崩溃问题求助
解决Electron打包Wiki.js整合应用后EXE崩溃无报错的问题
我来帮你排查这个问题,之前也遇到过类似的Electron打包原生模块崩溃的情况,咱们一步步来定位和解决:
1. 优先解决原生模块(sqlite3)的asar打包问题
这是最常见的崩溃原因——sqlite3是原生模块,打包进asar压缩包后,Electron无法正确加载它的二进制文件。你需要修改package.json的build配置,把sqlite3相关文件排除在asar之外:
"build": { "productName": "wiki.js-electron", "appId": "com.electron.wiki", "directories": { "output": "build" }, "asar": true, "asarUnpack": [ "node_modules/sqlite3/**/*" ] }
这样打包时,sqlite3的原生二进制文件会被放在app.asar.unpacked目录下,Electron就能正常读取了。
2. 替换固定延时为服务器启动完成后的回调
你当前用9秒固定延时加载页面,打包后环境差异可能导致服务器还没启动就加载页面,进而引发崩溃。改为监听服务器启动事件:
修改server/index.js,返回启动完成的Promise:
const express = require('express'); const path = require('path'); const app = express(); module.exports = new Promise((resolve) => { const server = app.listen(3000, () => { console.log('Server running on port 3000'); resolve(); }); }); // 这里添加你的wiki.js相关路由、静态文件配置,注意用绝对路径 app.use(express.static(path.resolve(__dirname, 'public')));
修改main.js,等待服务器启动后再加载页面:
const { app, BrowserWindow } = require('electron'); const path = require('path') let winGlobal; // 等待服务器启动完成后加载页面 require('./server/index.js').then(() => { if (winGlobal) { winGlobal.loadURL('http://localhost:3000'); } }); function createWindow() { const win = new BrowserWindow({ width: 1200, height: 900, webPreferences: { nodeIntegration: false, contextIsolation: true // 开启上下文隔离,提升安全性 } }) winGlobal = win; // 先加载一个本地加载页面,避免用户等待时无响应 win.loadFile(path.join(__dirname, 'loading.html')); } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } })
3. 确保所有文件路径使用绝对路径
打包后相对路径可能失效,比如wiki.js的静态文件、数据库文件,都要用path.resolve或app.getPath构建绝对路径:
数据库路径示例(修改server/index.js):
const sqlite3 = require('sqlite3').verbose(); const { app } = require('electron'); const userDataPath = app.getPath('userData'); // 获取用户可读写的数据目录 const dbPath = path.join(userDataPath, 'wiki.db'); const db = new sqlite3.Database(dbPath);
把数据库放在用户数据目录,避免应用安装目录(只读)的写入权限问题。
4. 捕获崩溃日志排查剩余问题
如果以上步骤还没解决,开启Electron崩溃日志来定位具体原因:
在main.js最顶部添加:
const { crashReporter } = require('electron'); crashReporter.start({ productName: 'wiki.js-electron', uploadToServer: false // 日志存本地 });
Windows下日志会存在%USERPROFILE%\AppData\Roaming\wiki.js-electron\Crashpad\reports,查看日志就能知道崩溃的具体堆栈信息。
内容的提问来源于stack exchange,提问作者Wang Liang
相关产品推荐
相关产品推荐

