Electron生产模式页面加载失败,开发模式正常,求解决方案
问题背景
执行yarn make生成可执行文件后,启动时出现以下错误:
electron: Failed to load URL: http://localhost:3000/main_window with error:
ERR_CONNECTION_REFUSED
该错误仅在生产模式下出现,开发模式运行正常。
最初尝试在main进程中区分开发/生产模式加载页面,代码如下:
import isDev from 'electron-is-dev' const createWindow = (): void => { // Create the browser window. const mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY } }); // and load the index.html of the app. isDev ? mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY) : `file://${path.join(__dirname, '../build/index.html')}` // Open the DevTools. if (isDev ) { mainWindow.webContents.openDevTools(); } };
修改后错误消失,但生产模式下窗口页面空白,开发模式则能正常显示"Got Finally!!"消息,说明生产环境页面未正确加载。
环境信息:
- Electron: 19
- 操作系统: Ubuntu 22.04
更新1:修正路径与语法问题
经提示后,修正了三元运算符未调用loadURL和路径错误的问题,修改后的代码:
mainWindow.loadURL(isDev ? MAIN_WINDOW_WEBPACK_ENTRY : `file://${path.join(__dirname, '../renderer/main_window/index.html')}`)
验证路径正确:
console.log(path.join(__dirname,'../renderer/main_window/index.html')) => /home/raphy/ForgeTypescriptReactWebpack/out/forgetypescriptreactwebpack-linux-x64/resources/app/.webpack/renderer/main_window/index.html
目标目录文件列表:
raphy@raohy:~/ForgeTypescriptReactWebpack/out/forgetypescriptreactwebpack-linux-x64/resources/app/.webpack/renderer/main_window$ ls -lah total 3,5M drwxrwxr-x 2 raphy raphy 4,0K gen 4 12:17 . drwxrwxr-x 3 raphy raphy 4,0K gen 4 12:17 .. -rw-rw-r-- 1 raphy raphy 386 gen 4 12:17 index.html -rw-rw-r-- 1 raphy raphy 3,4M gen 4 12:17 index.js -rw-rw-r-- 1 raphy raphy 1,8K gen 4 12:17 preload.js
但页面仍无法正常加载,以下是具体排查和解决建议:
排查与解决步骤
打开生产模式DevTools查看报错
临时在生产模式下开启DevTools,查看控制台的具体错误信息(比如资源加载失败、JS执行错误等):// 在createWindow函数中添加,测试完成后移除 mainWindow.webContents.openDevTools();验证index.html的脚本引用
打开生成的index.html文件,确认内部的index.js引用路径是否正确,比如是否使用了相对路径./index.js,避免绝对路径导致的加载失败。使用
loadFile替代loadURL
Electron的loadFile方法会自动处理本地文件路径和file://协议,比手动拼接URL更可靠:mainWindow.loadFile(path.join(__dirname, '../renderer/main_window/index.html'));检查Webpack构建配置
确认Electron Forge的Webpack插件中,渲染进程main_window的入口配置、输出路径是否正确,确保构建时生成了完整的bundle文件,且路径与代码中引用的一致。检查内容安全策略(CSP)
查看index.html中的CSP meta标签,确保允许加载本地脚本和资源,比如:<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">避免因CSP限制导致脚本无法执行。
验证路径解析
用path.resolve生成绝对路径,避免path.join可能出现的路径拼接问题:const htmlAbsolutePath = path.resolve(__dirname, '../renderer/main_window/index.html'); mainWindow.loadFile(htmlAbsolutePath);
内容的提问来源于stack exchange,提问作者Raphael10

