Search code examples
node.jselectronelectron-forge

Electron Forge - Can't use ipcRenderer in the renderer file


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.


Solution

  • 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"
                  }
                }
              ]
            }
          }
        ]
      ]