Electron Forge - 无法在渲染器文件中使用 ipcRenderer
2020-06-19
6997
我刚刚使用以下命令创建了一个新应用程序:
npx create-electron-app my-new-app --template=typescript-webpack
在 renderer.ts 中,我添加了以下代码
import "./index.css";
import { ipcRenderer } from "electron";
但是当我运行 npm run start 时,浏览器控制台中出现以下错误
Uncaught ReferenceError: require is not defined
更新 我尝试过的方法:
webpack.plugins.js
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
const webpack = require("webpack");
module.exports = [
new ForkTsCheckerWebpackPlugin(),
new webpack.ExternalsPlugin("commonjs", ["electron"]),
];
但是它仍然不起作用。
3个回答
找到解决方案
解决方案是在预加载脚本中使用 ipcRenderer。
preload.ts
import { ipcRenderer } from "electron";
index.ts
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: any;
const mainWindow = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
});
package.json
"plugins": [
[
"@electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.ts",
"name": "main_window",
"preload": {
"js": "./src/preload.ts"
}
}
]
}
}
]
]
Georgian Stan
2020-06-19
解决方案是使用
electron
中的
ContextBridge
API 用于 electron-forge
react+webpack
模板
preload.js
import { ipcRenderer, contextBridge } from "electron";
contextBridge.exposeInMainWorld("electron", {
notificationApi: {
sendNotification(message) {
ipcRenderer.send("notify", message);
},
},
batteryApi: {},
fileApi: {},
});
main.js
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
worldSafeExecuteJavaScript: true,
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
});
ipcMain.on("notify", (_, message) => {
new Notification({ title: "Notification", body: message }).show();
});
package.json
"plugins": [
[
"@electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.js",
"name": "main_window",
"preload": {
"js": "./src/preload.js"
}
}
]
}
}
]
]
app.jsx
import * as React from "react";
import * as ReactDOM from "react-dom";
class App extends React.Component {
componentDidMount() {
electron.notificationApi.sendNotification("Finally!");
}
render() {
return <h1>contextBridge</h1>;
}
}
ReactDOM.render(<App />, document.body);
Sathishkumar Rakkiyasamy
2021-07-29
如果您使用的是 typescript,则需要将其添加到您的 renderer.ts 文件中:
declare global {
interface Window {
electron: {
funcName: () => void;
};
}
}
然后您可以使用
window.electron.funcName()
。
Mohammed Agboola
2022-01-29