javascript - 内置到exe文件后,Electron应用程序无法正常运行

标签 javascript json electron

我刚刚完成了 Electron 测试项目的工作。问题是,当我使用 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()
  }
})
任何帮助将不胜感激。谢谢。

最佳答案

首先,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时。

关于javascript - 内置到exe文件后,Electron应用程序无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62627938/

相关文章:

javascript - 运行 Electron 时不渲染JSX组件

javascript - 使用express.json和bodyParser一样吗?

windows - 带 Electron 控件的无框窗口 (Windows)

javascript - 使用 AngularJS 服务构建 html 部分

json - 从 Swift 发送到 Node.js 的无效 JSON

javascript - 将 PHP 变量传递到 Flot 图表中

php 和 mysql db 从 Json 文件插入

electron - 改进了descjop项目的clojurescipt repl功能

javascript - jQuery 验证依赖表达式

javascript - 连续创建背景过渡