简短介绍
我一直在关注有关从渲染和主进程进行通信的官方 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 中的解决方案,但我找不到任何解决方案,所以任何帮助将不胜感激。
重现项目和错误的步骤
初始化项目并使用所需的编辑器打开。
npx create-electron-app app
cd app
code .
然后编辑
index.js
并添加nodeIntegration: true
.编辑您
index.html
的添加<script src="renderer.js"></script>
在和文件
renderer.js
旁边的 src 文件夹中创建一个新文件。index.html
index.js
现在你应该有以下树:
+-src
---index.css
---index.html
---index.js(这是你的 main.js)
---renderer.js(这是你的 renderer.js)将示例代码添加到 index.js 和 renderer.js
运行以下命令
npm start
,将打开一个新窗口并运行 Electron 应用程序。