0

简短介绍

我一直在关注有关从渲染和主进程进行通信的官方 Electron 文档(https://www.electronjs.org/docs/api/ipc-main
,但我无法让它工作。

错误

在尝试发送消息示例时,我在 JS 控制台中收到此错误:
❌ Uncaught ReferenceError: require is not defined

示例代码

这是我在main.js中的最后几行

// In main process.
const { ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
  console.log(arg) // prints "ping"
  event.reply('asynchronous-reply', 'pong')
})

ipcMain.on('synchronous-message', (event, arg) => {
  console.log(arg) // prints "ping"
  event.returnValue = 'pong'
})

这就是我在我的render.js中所拥有的

// In renderer process (web page).
const { ipcRenderer } = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"

ipcRenderer.on('asynchronous-reply', (event, arg) => {
  console.log(arg) // prints "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')

我得到的错误在这部分const { ipcRenderer } = require('electron')

https://www.electronjs.org/docs/api/ipc-main#sending-messages

这就是我在我的内部调用我的render.js的方式<head>

<script defer src="../scripts/render.js"></script>

截屏

关于错误的屏幕截图

我试过的

我已经关注了这个相关的 Q/A,但我仍然得到同样的错误: Using ipc in Electron to set global variable from renderer
还有这个:Uncaught ReferenceError: require is not defined in Electron
And this:“Uncaught SyntaxError: Cannot use import statement导入 ECMAScript 6 时在模块之外

我看到有人说您需要在 main.js 中启用nodeIntegration的,我已启用它但仍然抛出错误:

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1280,
    height: 900,
    icon: path.join(__dirname, '../render/assets/favicon.png'),
    autoHideMenuBar: true,
    webPrefrerences: {
      nodeIntegration: true,
    }
  });

我还尝试转换为ES6 模块语法

import { ipcRenderer } from 'electron';

同时还像这样添加type="module"

  <script type="module" defer src="../scripts/render.js"></script>

但是错误是:
❌<strong>Uncaught SyntaxError: Cannot use import statement outside a module

我一直在寻找 SO 中的解决方案,但我找不到任何解决方案,所以任何帮助将不胜感激。

重现项目和错误的步骤

  1. 初始化项目并使用所需的编辑器打开。
    npx create-electron-app app cd app code .

  2. 然后编辑index.js并添加nodeIntegration: true.

  3. 编辑您index.html的添加<script src="renderer.js"></script>

  4. 在和文件renderer.js旁边的 src 文件夹中创建一个新文件。index.htmlindex.js

  5. 现在你应该有以下树:

    +-src
    ---index.css
    ---index.html
    ---index.js(这是你的 main.js)
    ---renderer.js(这是你的 renderer.js)

  6. 将示例代码添加到 index.js 和 renderer.js

  7. 运行以下命令npm start,将打开一个新窗口并运行 Electron 应用程序。

  8. 控制台抛出错误。 示例错误

4

1 回答 1

0

我的main.js中有错字

这是webPreferences而不是 webP r references!

nodeIntegration默认为False,这就是我不能使用 require 的原因。

于 2021-07-25T17:31:33.897 回答