首页 > 解决方案 > 内置到 exe 文件后,Electron 应用程序无法正常运行

问题描述

我刚刚完成了一个电子测试项目。问题是当我使用电子打包程序将应用程序打包成可执行文件时,我的 main.html 文件不会加载到窗口中。但是,当我使用它运行时,npm start它工作得非常好。我检查了我的文件路径是否有任何错误,但这也很好。

这是我的 package.json 文件 -

{
  "name": "test",
  "version": "1.0.0",
  "description": "Just a test app",
  "main": "src/main.js",
  "scripts": {
    "start": "electron ."
  },
  "author": "Ray",
  "license": "MIT",
  "devDependencies": {
    "electron": "^9.0.5"
  },
  "dependencies": {
    "electron-packager": "^15.0.0"
  }
}

这是我的 main.js

const { app, BrowserWindow } = require('electron')

function createWindow () {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // and load the index.html of the app.
  win.loadFile('./app/main.html')
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

任何帮助将不胜感激。谢谢。

标签: javascriptjsonelectron

解决方案


首先electron-packager应该是 devDependencies 的一部分,而不是依赖项。

第二:你怎么打包?如果您使用 asar 文件,则需要查看路径。包装时会发生变化。所以我建议你使用类似的东西

win.loadURL(`file://${__dirname}/main.html`)

或者

win.loadURL(url.format({
    pathname: path.join(__dirname, 'main.html'),
    protocol: 'file:',
    slashes: true
}));

加载您的html时。


推荐阅读