I just created a new application using the following command:
npx create-electron-app my-new-app --template=typescript-webpack
Inside the renderer.ts I added the following code
import "./index.css";
import { ipcRenderer } from "electron";
But when I run npm run start I have the following error in Browser Console
Uncaught ReferenceError: require is not defined
Update What I've tried:
webpack.plugins.js
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
const webpack = require("webpack");
module.exports = [
new ForkTsCheckerWebpackPlugin(),
new webpack.ExternalsPlugin("commonjs", ["electron"]),
];
But it still doesn't work.
Found Solution
The solution is to use ipcRenderer in a preload script.
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"
}
}
]
}
}
]
]
The solution is using the ContextBridge
API from electron
for electron-forge react+webpack template
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With