使用Nuxt 3构建Electron可执行文件时白屏问题求助
解决方案:Nuxt 3 + Electron 打包后白屏问题修复
核心问题分析
你的问题主要出在三个地方:
- Electron主进程代码存在语法错误,且未区分开发/生产环境的资源加载路径
- Nuxt打包后的静态资源路径配置缺失
- Electron-builder的打包资源配置不完整
步骤1:修复Electron主进程代码
替换electron/main.ts内容,解决实例未保存、路径错误、DevTools无法打开的问题:
import { app, BrowserWindow, Menu } from 'electron' import path from 'path' function createWindow() { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { contextIsolation: true, nodeIntegration: false, }, }) // 区分开发/生产环境加载逻辑 if (process.env.VITE_DEV_SERVER_URL) { mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL) mainWindow.webContents.openDevTools() // 开发环境自动打开调试工具 } else { // 生产环境加载Nuxt打包后的本地index.html mainWindow.loadFile(path.join(__dirname, '../dist/index.html')) // 生产环境需要调试的话,取消下面注释 // mainWindow.webContents.openDevTools({ mode: 'detach' }) } // 隐藏默认菜单(可选,根据需求调整) mainWindow.setMenu(null) } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() })
步骤2:调整Nuxt配置
修改nuxt.config.ts,确保静态资源路径适配桌面端:
export default defineNuxtConfig({ devtools: { enabled: true }, ssr: false, router: { options: { hashMode: true, }, }, modules: ['nuxt-electron'], electron: { build: [ { entry: 'electron/main.ts', }, ], }, // 关键:设置相对路径,确保打包后静态资源能正确加载 app: { baseURL: './', }, })
步骤3:完善package.json配置
更新package.json,添加打包脚本并修正Electron-builder配置:
{ "name": "nuxt-app", "private": true, "version": "1.0.0", "description": "My Electron App Description", "type": "module", "main": "dist-electron/main.js", "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", "postinstall": "nuxt prepare", "electron:build": "nuxt build && electron-builder --win" }, "dependencies": { "nuxt": "^3.10.3", "vue": "^3.4.19", "vue-router": "^4.3.0" }, "devDependencies": { "electron": "^28.2.4", "electron-builder": "^24.12.0", "nuxt-electron": "^0.7.0", "vite-plugin-electron": "^0.28.2", "vite-plugin-electron-renderer": "^0.14.5" }, "build": { "appId": "com.yourcompany.yourapp", "win": { "target": "nsis" }, "files": [ "dist/**/*", "dist-electron/**/*" ] } }
排查验证步骤
- 先执行
npm run build && npm run preview,确认Nuxt打包后的网页能正常访问。如果这里也白屏,说明是Nuxt本身的打包问题,优先检查路由、静态资源路径。 - 执行
npm run electron:build打包桌面应用,测试生成的exe文件。 - 如果仍有问题,打开生产环境的DevTools(取消main.ts中对应注释),查看控制台的报错信息(比如资源404、JS语法错误),针对性修复。
内容的提问来源于stack exchange,提问作者Everson
相关产品推荐
相关产品推荐

