【问题标题】:Electron - preload.js is not loaded and error is occurred on Windows 10Electron - preload.js 未加载并且在 Windows 10 上发生错误
【发布时间】:2021-01-02 18:05:53
【问题描述】:

当我在 Windows 10 上构建 npm start 应用程序时,它无法正常运行,而在 macOS 上运行良好。

package.json

{
  "name": "SimpleTimer",
  "version": "1.0.0",
  "productName": "SimpleTimer",
  "copyright": "",
  "description": "",
  "main": "main.js",
  "scripts": {
    "start": "node_modules/.bin/electron .",
    "test": "echo \"Error: no test specified\" && exit 1",
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "electron": "^10.1.2"
  }
}

我收到以下错误消息。

TypeError: ipcMain.handle is not a function 此处适用:

main.js

ipcMain.handle("ipc-timer-start", () => {
  if ( isWorking === true ) {
    return true
  }
  else {
    StartTimer();
    isWorking = true;
  }
  return true;
});

这个函数是来自ipcRenderer.invoke()的ipc通信的接收者,写在preload.js。就是下面源码中TimerStart api中的invoke()方法。

preload.js

const { contextBridge, ipcRenderer} = require("electron");

contextBridge.exposeInMainWorld(
  "api", {
    TimerStart: () =>
        ipcRenderer.invoke("ipc-timer-start")  /*** HERE ***/
            .then(result => result)
            .catch(err => console.log(err)),

    TimerStop: () => ipcRenderer.send("ipc-timer-stop"),

    TimerReset: () => ipcRenderer.send("ipc-timer-reset"),

    DisplayTimer: (channel, listener) => {
      ipcRenderer.on("ipc-display-timer", (event, arg) => listener(arg));
    }
  }
);

当然,preload.js 是在创建 BrowserWindow 时指定的。

main.js

 mainWindow = new BrowserWindow({
    title: config.name,
    width: 1024,
    height: 640,
    minWidth: 1024,
    minHeight: 640,
    webPreferences: {
      worldSafeExecuteJavaScript: true,
      nodeIntegration: false,
      contextIsolation: true,
      preload: __dirname + '/preload.js'  /*** HERE ***/
    }
  });

跳过此错误消息对话框后,我使用 DevTools 进行了检查,看起来 preload.js 不是从 Unable to load preload script: 的语句中加载的。

鉴于这些陈述,preload.js 似乎没有正确包含在构建中,我该怎么办?

再一次,它在 macOS 上运行良好,但由于这些问题,它在 Windows 10 上无法正常运行。

【问题讨论】:

    标签: javascript node.js windows electron preloadjs


    【解决方案1】:

    我能够自己解决这个问题。

    这个问题不是在电子中,而是在我的Parallels Desktop for Mac 环境中。

    我试图通过 Parallels 网络驱动器让 Electron 工作目录在 Windows 10 上运行,但它似乎无法正确识别构建文件路径。

    目前,即使您在本地安装 Electron 而不是全局安装,它似乎也无法正确构建。

    npm install electron@latest --save-dev
    

    似乎可以在 macOS 上构建的项目无法直接在 Windows 10 上构建。

    Electron 是在 Windows 10 上构建的“electron .”命令,它似乎提取了C:\Users\[UserName]\AppData\Roaming\npm\ 路径上的必要文件。具体原因我也不知道,但是好像和本地安装的 Electron 不一致。

    如果您想在 Windows 10 上运行您的项目,请复制项目目录并输入“npm install”命令重新安装 Electron 等 Node 模块。它会自动重新安装package.json中列出的依赖包。

    结果,我终于可以毫无问题地构建“node_modules/.bin/electron .”来构建它了。

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 2019-06-03
      • 2022-07-10
      • 1970-01-01
      • 2022-12-27
      • 2020-03-24
      • 2021-12-07
      • 1970-01-01
      相关资源
      最近更新 更多