Electron: Requiring electron outside of main.js causes a TypeError

Created on 22 Sep 2016  ·  82Comments  ·  Source: electron/electron

  • Electron version: 1.3.5
  • Operating system: Mint 17

Hello

I am using Electron with React.js and babelify, among other plugins (list at the bottom).
Attempting to use require('electron'), for example to gain access to electron's BrowserWindow, results in the console showing the following error:
index.js:4 Uncaught TypeError: fs.readFileSync is not a function

I can, however, use const electron = require('electron'); in main.js. For what it's worth, I am also using watchify to pack everything into a js bundle.

Here is the complete list of dependencies in my package.json:

"devDependencies": {
        "axios": "^0.9.1",
        "babel-preset-es2015": "^6.6.0",
        "babel-preset-react": "^6.5.0",
        "babelify": "^7.2.0",
        "classnames": "^2.2.3",
        "electron": "^1.3.5",
        "electron-reload": "^0.2.0",
        "jquery": "^2.2.3",
        "react": "^0.14.8",
        "react-autocomplete": "^1.0.0-rc2",
        "react-dom": "^0.14.7",
        "react-sound": "^0.4.0",
        "soundmanager2": "^2.97.20150601-a"
    },
blockeneed-info ❌

Most helpful comment

For anyone encountering this problem in the future and reading this thread, using window.require instead of require is one possibility of avoiding the conflict between electron's and browserify's require function.

All 82 comments

index.js:4 Uncaught TypeError: fs.readFileSync is not a function

Can you include line 4 of index.js here? Or a fuller stack trace?

I believe it is referring to index.js of electron, which is itself located in node-modules of the project. Here are the contents of this file:

var fs = require('fs')
var path = require('path')

module.exports = path.join(__dirname, fs.readFileSync(path.join(__dirname, 'path.txt'), 'utf-8'))

The entire stack trace suggests a conflict with React.js:

Stack trace

What happens if you run require('fs').readFileSync from the Console tab of the dev tools?

It looks like the electron-prebuilt node module (the file you pasted) is ending up in your packaged app which I don't think you want since it should use the built-in electron require instead.

@nukeop How are you launching your app. Your `start script should look like.

"scripts": {
  "start": "electron ."
}

I have a feeling you are attempting to run your main.js with node

node main.js

Which won't work

What happens if you run require('fs').readFileSync from the Console tab of the dev tools?

Right after this error is thrown, I am able to run require('fs').existsSync in console to print a definition of the function. It also works before the error.

It looks like the electron-prebuilt node module (the file you pasted) is ending up in your packaged app which I don't think you want since it should use the built-in electron require instead.

I have a watchify instance running in the background as I'm developing which is continually updating my package. I defined it in scripts section of package.json like this:

"watch": "watchify app/app.js -t babelify -o public/js/bundle.js --debug --verbose"

Any advice on avoiding bundling electron-prebuilt?

@nukeop Electron supports require internally so you don't need to use browserify.

As far as I am aware, I'd you want to use browserify, you have to exclude "electron".

Interesting, could it be that watchify/browserify is ruining this? It has worked ok so far.

Now I am not sure how to run the program without it.

Literally just run

electron .

From your main app folder, you don't need to bundle anything when using Electron as it has a full node environment internally.

_I'm going to close this out as it is a Browserify issue_

That's what I've been doing all along, packing the program into a single .js file, which is included in a simple html file with:

  <script src="public/js/bundle.js">
  </script>

And everything works, except when I use require. This is a problem with interaction between the two modules.

If I do not pack the whole program into a bundle, I have no easy way of running it, as my main.js only starts electron and loads the html file that includes the bundle.

@nukeop The renderer process inside Electron has access to a full node/commonjs environment as well, so you don't need to bundle anything.

If I do not pack the whole program into a bundle, I have no easy way of running it, as my main.js only starts electron and loads the html file that includes the bundle.

I'm not sure I understand here, any script you load in your HTML file has a full commonjs environment and can therefore use require to load in extra files without browserifying anything

For anyone encountering this problem in the future and reading this thread, using window.require instead of require is one possibility of avoiding the conflict between electron's and browserify's require function.

FWIW, I ran into the same issue trying to use electron in the renderer process with create-react-app that uses webpack in the backend instead of browserify. window.require seems to solve it for me too though I'm not entirely clear why.

Edit: I figured out why :-) We want to require electron during runtime from the nodejs environment provided at the runtime rather than the nodejs environment used during compilation by webpack. By default, globals are bound to window and webpack compilation ignores the window global - hence window.require works.

Another way to tell webpack to ignore a global name is to use a comment like /*global Android*/ in the JS file. In another project using CRA built app in an Android WebView, I used the above to get access to a Java object exposed to JS through the JavaScript interface provided by Webview.

@nukeop - thanks for your last post; it helped me a lot. window.require worked for me.

yep fixed my create react app / webpack issue.
change

import electron, { ipcRenderer } from 'electron'

to

const electron = window.require("electron")

@srinathh how are you exposing/loading your CRA app as renderer in your main? are you building first (and modifying the html static resource paths)

Yes my workflow currently is to basically run npm run build using the CRA scripts and then run the output in the build folder with electron. You don't need to modify the static resource paths by hand. In the package.json for CRA scripts, you just need to set the homepage like this and the paths will be appropriately set.

    "homepage": "./"

Additionally, I have main.js and package.json for the electron app in the public folder. So running the build automatically copies them over & you can just run electron build/ to start your app.

I'd actually like to be able to do the npm start with electron for development but I haven't gotten around to figuring how to make that work. I'm guessing i'll have to do an eject and modify the script by hand.

If you'd like to seen an example of the setup - take a look at https://github.com/srinathh/snippetfu

I'm not using Electron, but Node-Webkit (nw.js).
Using window.require did also fix my issue. Thanks very much for this!

@nukeop window.require did the trick for me as well thank you very much! 🎉

@nukeop I got same error, but it is solved window.require trick, thanks a lot!

window.require did solve the issue of fs.existsSync is not a function but it lead to another error : window.require is not a function. How shall I solve it?

@steric85 are you using browserify, babel or webpack? you might need to transpile your code

@Alxmerino I am using webpack.

make sure you're compiling your code

@steric85, I faced the window.require is not a function in typescript, I managed to fix it this way:

declare global {
  interface Window {
    require: any;
  }
}

const electron = window.require('electron');

I'm using the above method for accessing the ipcRenderer from electron in my Angular app but Angular change detection is not working when I update an Observable using an ipcRenderer message handler.
Is it because Angular doesn't know that ipcRenderer is an EventEmitter and that it needs to run change detection when ipcRenderer events come in?

in Angular 2 I used to call applicationRef.tick() to explicitly tell angular to refresh its state. https://angular.io/api/core/ApplicationRef

I'm facing a very similar problem to @nukeop and @srinathh: I set up my Electron + React + Webpack project following this article guide, where the author at the end mentions the trick with window.require. I only require('electron') two places in my project; in the entry point for Electron, and in a JavaScript controller class that is required by some React components. In my Electron entry point file I simply do const electron = require('electron');, since it should be running in the main process (right?), and in my controller class I do const Electron = window.require('electron').remote; followed by const Jsonfile = Electron.require('jsonfile');, which should be the way to do it since it's running in the renderer process. But I get the same error as @nukeop ("TypeError: fs.ExistsSync is not a function") at line six in node_modules/electron/index.js which looks like this:

var fs = require('fs')
var path = require('path')

var pathFile = path.join(__dirname, 'path.txt')

if (fs.existsSync(pathFile)) {
  module.exports = path.join(__dirname, fs.readFileSync(pathFile, 'utf-8'))
} else {
  throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')
}

I've tried deleting node_modules/electron and installing again.
I'm using Electron 1.7.5 on macOS 10.12.6, and start my project using npm run dev as setup in the article.

Update; I found the require that caused my error, I tried doing require('electron-react-devtools') in my React index.js. Changing it to const ReactDevtools = Electron.require('electron-react-devtools'); stopped the errors, but now it seems I can't call .inject() in the ReactDevtools instance ("is not a function"), but that might not be something to discuss here.

@steric85 It is because you running the app in webpage environment => you must run the app in Electron environment (Nodejs environment)

  • require('electron') => Webpack will bundle electron module to bundle.js => electron use fs module => Webpack doesn't understand
  • window.require('electron') => Webpack will ignore require function
  • In webpage environment, window.require will be undefined
  • In nodejs environment, window.require will work
    => Open your app in Electron window (not in browser window like Chrome, Firefox, etc.

I'm still getting window.require is not a function. I'm using Electron with React Starter Kit (https://github.com/kriasoft/react-starter-kit). Everything is working nicely, except this.

I've set my Electron app to load my app from the web, so the app is not running locally:
https://gist.github.com/holgersindbaek/68f6db82f507967a51ca75c527faeff6

What I'm trying to do, is call the ipcRenderer in one of my React files. I'm not sure if it's even possible when my app is being loaded from the web though. Any suggestions?

@holgersindbaek You shouldn't view your app in browser like Chrome, Firefox, etc. It won't work because it is the webpage environment.
You should view your app in an Electron window.

I am, but I'm using Electron in a way, where I'm loading my app from the website on each launch. Essentially I'm showing a website in my electron app. See the above file. I just want to make sure that there's really nothing I can do?!

Electron can load any URLs. In order to load a URL you should use this function mainWindow.loadURL(url)
=> In electron window view, that URL javascript code can access require, ipc, etc.

Ok. I'll try that.

window.require on electron didn't work, but window.require for fs did.

Not really sure why. But it's working and since it's a small personal project I'm not going to push the issue.

Thanks @nukeop

Hi, This is my package.json, I am using webpack, none of these did solve my problem, does anybody have a solution? After I use window.require, I got error "window is not defined"

'use strict';

var electron = require('electron')
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var mainWindow = null;

app.on('ready', function() {
mainWindow = new BrowserWindow({width: 800, height: 600});

mainWindow.loadURL('file://' + __dirname + '/index.electron.html');

mainWindow.webContents.openDevTools();

});

I'm using typescript and I had to use

const electron = (<any>window).require("electron");

to get my renderer to communicate with my main. Hope this helps someone.

This worked for me.
For e.g. if you want to require remote, then

declare const window: any;
const { remote } = window.require('electron');

Hi, thanks man.

On Sun, Dec 3, 2017 at 9:29 PM, Michael - ሚካኤል ሰልጠነ <
[email protected]> wrote:

This worked for me.
For e.g. if you want to require remote, then

declare const window: any;
const { remote } = window.require('electron');


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/electron/electron/issues/7300#issuecomment-348801405,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ARDyd4c3aOkMbb058xklujMMbnmaoxKGks5s8uGVgaJpZM4KDU6t
.

@solominh Thanks for your explanations here. However I have a similar configuration as @holgersindbaek, which environment is a preload script in a webview?

Info:

  • My electron entry runs mainWindow.loadURL(url), where url is a local index.html
  • This index.html has a <webview>
  • The webview has a preload field which loads inject.js, and this script does the window.require('electron').

Remarks:

  • If I use const electron = require('electron'), I have the error fs.readFileSync is not a function
  • If I use const electron = window.require('electron'), I have the error window.require is not a function.
  • inject.js is bundled through webpack (can paste config if relevant).

EDIT: Solved for me using <webview nodeintegration="true"> and window.require. Leaving note here for future reference.

window.require worked for me! Thanks guys!

https://imgur.com/a/ekWwD

error message in browser when i tried this

Forgot to revert nodeIntegration: false which disables even window.require()... stupid mistake. Hope this spares someone an hour of researching.

@phil294 Thanks man! you really saved an hour of researching.

Hi @micsel ,
I included declare const window: any;
but it is throwing syntax error.
Any ideas why?

Ya, put declare const window: any; at the top, just after where the imports are.

If you get window.require is not a function and you are using Angular-CLI, use the following to instantiate the Window interface:

./src/typings.d.ts

declare var window: Window;
interface Window {
    require: any;
}

Then you can use this to include electron:
const { ipcRenderer } = window.require('electron');

if you are using angular 2+ in electron app then import "ngx-electron" lib and use this in any.componets.ts

import { ElectronService } from 'ngx-electron';

//constructor
constructor(
    private elt: ElectronService
  ){
  var fs = this.elt.remote.require('fs');
}

I am using react js with electron and when i run this line into terminal yarn run start it provides me error Uncaught Type Error: window.require is not a function i am not using typescript how declare window in React Js

People who are still facing the issue, somehow doing a window.require() spoils the consistency of using import statements throughout the codebase. An easy alternative is to set your webpack target to electron-renderer. If using Create React App, ejecting can be a mess. Hence, you can use this package which does the webpack hooking for you and you can use for eg., import fs from 'fs' in your React components (or any other node module ), happily in your life :)

On windows with Vue CLI 3, window.require will work but will require a full path instead of a relative path from "node_modules/".

But similar to the React case, webpack can be configured properly for Vue by editing vue.config.js. "require" will then work as expected.

vue.config.js:

module.exports = {
    configureWebpack: config => {
      if (process.env.NODE_ENV === 'production') {
        config.output.publicPath = `${process.cwd()}/dist/`
      }
      config.target = 'electron-renderer'
    }
  }

router.js (this is just an example, it would work in any other vue js file)

const Store = require("electron-store");
const store = new Store();

_I almost don't want to add this but it would have saved me an hour or two of debugging._

I had to rm -rf node_modules && npm install to fix this issue. I was then able to remove the window from window.require and things started working again. Hopefully that helps somebody else.

@cperthuis I just want to say THANK YOU!! Hahah I am not even using Vue, but logical thinking led me to figure out that i can change my webpack.config.js to have a target property :)
image
WORKED LIKE A CHARM.

Hi,

window.require works in a dev local server environment but doesn't in a prod environment after building React app to a minified HTML file.

function createWindow() {
  win = new BrowserWindow({
    width: 1280,
    height: 720,
    icon: path.join(__dirname, 'assets/icons/png/64x64.png'),
    webPreferences: {
      nodeIntegration: true,
      preload: __dirname + '/preload.js'
    }
  })

  win.setPosition(0, 0)

  win.loadURL(isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, 'build/index.html')}`)
}

It works with localhost:3000 but not with file://${path.join(__dirname, 'build/index.html')}

https://imgur.com/EE7jxZq

@cperthuis, your fix worked for un-ejected CRA app using 'react-app-rewired'. thank you.
image

With Create-React-App 2, you can use the craco npm module:

https://www.npmjs.com/package/@craco/craco

Change react-scripts by craco in your package.json

craco.config.js

module.exports = {
    webpack: {
        configure: {
            target: 'electron-renderer'
        }
    }
};

And in you'll have access to your Electron context like that:

import Electron from 'electron';
const { dialog } = Electron.remote;

@Maxou44 thanks for the tip about craco & electron. It is just what I needed. In case anyone is looking for an example...

https://github.com/wwlib/cra-craco-electron-example

@wwlib No problem, happy to see it helped you 🥳

Forgot to revert nodeIntegration: false which disables even window.require()... stupid mistake. Hope this spares someone an hour of researching.

Thank you so much.

Please note that if you're loading remote content, it is important to set nodeIntegration to false: https://electronjs.org/docs/tutorial/security#2-disable-nodejs-integration-for-remote-content

Hi,
I am having the same error. When using window.require, the Uncaught TypeError: fs.readFileSync is not a function error is fixed but i came up with another error Uncaught TypeError: window.require is not a function.

Is there any suggestion on how to fix this. I am using browserify on node js.

For anyone still stuck on this: you'll get the error window.require is not a function unless you explicitly declare nodeIntergation as truewhen you declare your BrowserWindow:

new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
    }
});

The only one good enough solution I found is following:

  1. install as dev dependency react-app-rewired package
  2. Use this module to inject custom Webpack config without eject-ing the CRA:
 "scripts": {
   ...
    "start": "react-app-rewired start",
  },
  1. and add the file config-overrides.js with according content:
module.exports = function override (config, env) {
  config.target = 'electron-renderer'
  return config;
}

Thanks to: @Lilanga comment, @agrublev comment and creators of react-app-rewired.

Updated:
Actually the 2nd version of how to do the same: https://www.codementor.io/randyfindley/how-to-build-an-electron-app-using-create-react-app-and-electron-builder-ss1k0sfer

Updated2:
@nukeop I removed some misleading statements due to lack of time to follow debates regarding why not to use Browserify or why to use it and can't write down now detailed explanation what I meant. But I will keep personal opinion regarding that "just use window.require will solve the problem" seems very unreliable.

Incorrect how?

It's a React app which must be running inside Electron environment and not vice-versa

What?

_I almost don't want to add this but it would have saved me an hour or two of debugging._

I had to rm -rf node_modules && npm install to fix this issue. I was then able to remove the window from window.require and things started working again. Hopefully that helps somebody else.

Wow.. Tried EVERYTHING in this thread and missed your replay because there no upvotes.. Still got window is not a function..
removed and reinstalled node_modules and its working.

PS: you still need to do all the solutions but if you did everything
and still the same re install node_modules

You saved my day @joshuapinter !

Using react-create-app I found the same errors.
The solution so far was:
const electron = window.require("electron") in the electron part BrowserWindow add nodeIntegration:true in the following way.
mainWindow = new BrowserWindow({ width: 900, height: 680, webPreferences: { webSecurity: false, nodeIntegration: true } });

The only one good enough solution I found is following:

  1. install as dev dependency react-app-rewired package
  2. Use this module to inject custom Webpack config without eject-ing the CRA:
 "scripts": {
   ...
    "start": "react-app-rewired start",
  },
  1. and add the file config-overrides.js with according content:
module.exports = function override (config, env) {
  config.target = 'electron-renderer'
  return config;
}

Thanks to: @Lilanga comment, @agrublev comment and creators of react-app-rewired.

Updated:
Actually the 2nd version of how to do the same: https://www.codementor.io/randyfindley/how-to-build-an-electron-app-using-create-react-app-and-electron-builder-ss1k0sfer

Updated2:
@nukeop I removed some misleading statements due to lack of time to follow debates regarding why not to use Browserify or why to use it and can't write down now detailed explanation what I meant. But I will keep personal opinion regarding that "just use window.require will solve the problem" seems very unreliable.

This worked for me. Thank you

Problem with window.require is that it only works for the top level package.
e.g. If I'm using fs directly, it works. But If I'm using a package that has a dependency on fs then I still get an exception.

window.require it's not working for me when I call the function inside the React App. I got "TypeError: window.require is not a function".

App.js:
```javascript
import React, { useEffect, useState } from 'react';
import './App.css';

const ipcRenderer = window.require('electron').ipcRenderer;

function App() {

useEffect( () => {

    ipcRenderer.on('ping', (event, message) => { console.log(message) });

}, []);

return (
<div className = 'App'>
    <div className = 'Header-Arrow'></div>
    <div className = 'Box'>
        <p>Press ⌘ + ⇧ + 4</p>
    </div>
</div>
);

}

export default App;
````

Mainwindow variable on Main.js:
```javascript
// Create the browser window.
mainWindow = new BrowserWindow({
alwaysOnTop: true,
frame: false,
fullscreenable: false,
transparent: true,
titleBarStyle: 'customButtonsOnHover',
show: false,
width: 300,
height: 350,
webPreferences: {
nodeIntegration: true,
preload: __dirname + '/preload.js'
}
});

``` **Preload.js`**:

javascript window.ipcRenderer = require('electron').ipcRenderer;

What I am missing?

So, issue solved. I answer myself because maybe someone can benefit from it (I stucked for hours). If you have a Preload.js file, you don't need to call window.require('electron').ipcRenderer again from the Àpp.js (renderer); you call directly the variable as window.ipcRenderer like this:

App.js:

````javascript
import React, { useEffect, useState } from 'react';
import './App.css';

function App() {

useEffect( () => {

    window.ipcRenderer.on('ping', (event, message) => { console.log(message) });

}, []);

return (
<div className = 'App'>
    <div className = 'Header-Arrow'></div>
    <div className = 'Box'>
        <p>Press ⌘ + ⇧ + 4</p>
    </div>
</div>
);

}

export default App;
````

Mainwindow variable on Main.js:
javascript // Create the browser window. mainWindow = new BrowserWindow({ alwaysOnTop: true, frame: false, fullscreenable: false, transparent: true, titleBarStyle: 'customButtonsOnHover', show: false, width: 300, height: 350, webPreferences: { nodeIntegration: true, preload: __dirname + '/preload.js' } });
Preload.js:

javascript window.ipcRenderer = require('electron').ipcRenderer;

After running the app from the command line, the window generated by the React process will throw an error (ipcRenderer is undefined). Ignore it. The window generated by the Electron process (main app ) will work fine.

With Create-React-App 2, you can use the craco npm module:

https://www.npmjs.com/package/@craco/craco

Change react-scripts by craco in your package.json

craco.config.js

module.exports = {
    webpack: {
        configure: {
            target: 'electron-renderer'
        }
    }
};

I had the problems while require("fs") as well as window.require("fs"). Thanks to @Maxou44 for introduction CRACO in this discussion.

To solve the issue I made 3 changes in my project:

  1. Used CRACO as suggested by @Maxou44.
  2. In public/main.js(some might have named this file as electron.js), changed
    new BrowserWindow({ width: 1200, height: 800 })
    to
    new BrowserWindow({ width: 1200, height: 800, webPreferences: { nodeIntegration: true } })
  3. Replaced const fs = require("fs") to const fs = require("electron").remote.require("fs")

Refer this git repo by @wwlib for more clarification https://github.com/wwlib/cra-craco-electron-example

I read whole thread from top to bottom and nothing worked.
EXCEPT, @Saroopashree 's method above. Thanks @Saroopashree for sharing the solution.
I guess since react and webpack have changed somewhat since the start of the thread, the solutions above are obsolete. I may be wrong ofcourse but using above method worked.
This is what I did:

  1. Ran npm install craco -D
  2. Create config file craco.config.js and pasted following code
    module.exports = { webpack: { configure: { target: 'electron-renderer' } } };
  3. Updated new BrowserWindow({ width: 1200, height: 800, webPreferences: { nodeIntegration: true } }) in main.js. Ofcourse with different width and height.
  4. Ran npm start to start development server for react app created using create-react-app. This opened a tab with same errors. And I felt tired again.
  5. Ran npm run electron to run electron app.
    And Viola!!! I was able to see the page.

So thank you @Saroopashree.

If you are trying to access 'electron' or its other component inside a react component/class, then try this: #336757899

Thanks to @tumbledwyer for posting the link to a solution that works for me:

Updated:
Actually the 2nd version of how to do the same: https://www.codementor.io/randyfindley/how-to-build-an-electron-app-using-create-react-app-and-electron-builder-ss1k0sfer

The solution from Randy Findley:
Now, if you need to access the fs module like I did, you'll quickly hit the Module not found error

First, install Rescripts.

yarn add @rescripts/cli @rescripts/rescript-env --dev

Then, change the scripts tags in package.json from this...

"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",

to this

"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",

Now add a new file called .rescriptsrc.js with the following contents:

module.exports = [require.resolve('./.webpack.config.js')]

Finally add another new file called .webpack.config.js with the following contents:

// define child rescript
module.exports = config => {
  config.target = 'electron-renderer';
  return config;
}

Now you can use the fs module, no worries.

What @ledleds pointed out worked for me, using CRA with typscript and Electron. Then thing is that I declared webPreferences like this:

    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    },

so that seems to be overwriting/setting nodeIntegration to false, so setting it to true and relaunching the app solved the issue (you have to relaunch the app in order to load Electron window with that config)

setting nodeIntegration to true like this

    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true
    },

For anyone still stuck on this: you'll get the error window.require is not a function unless you explicitly declare nodeIntergation as truewhen you declare your BrowserWindow:

new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
    }
});

react-app-rewired

This was the only good solution I found in terms of scalability, I do not think anyone should rely on window.require

Why would window.require not be scalable?

For anyone who happens to be struggling with this or similar issues and is using Vue and vue-electron-builder, see here

For anyone still struggling with this especially regarding quitting the electron application through a react button please read on.

What helped for me was the following:

  1. When you declare your window make sure you set nodeIntegration: true as this is currently by default false for security reasons. Usually that is done in your electron.js file.

  2. As @packetstracer already mentioned: _you have to relaunch the app in order to load Electron window with that config_

mainWindow = new BrowserWindow({
//...
  webPreferences: {
    nodeIntegration: true,
  },
});
  1. Also in your electron.js put the following statement near the top this ensures that the ipcMain will listen on the event _"close-me"_:
const { ipcMain } = require("electron");
ipcMain.on("close-me", (evt, arg) => {
  app.quit();
});
  1. In the react component where your _"close"_-button is located add the following window.require statement after your imports. The usual require did not work:
const ipcRenderer = window.require("electron").ipcRenderer;
  1. And in order to close your application call the following statement. It should send the event _"close-me"_ to the ipcMain:
<Button label="close" onClick={(e) => ipcRenderer.send("close-me")} />

Feel free to comment and give feedback I am still new to electron.
I know the context with the quit button is unrelated but I could not find a better suited thread. Please feel free to point me to another more suitable thread if there is one.

My configuration:

"electron": "9.2.0",
"electron-builder": "22.8.0",
"electron-packager": "15.0.0",

solved for me!! Thanks @nukeop

`
`

Does anyone know how to set up the proper type in typescript?

I have the following at the moment

export const electron = window.require('electron').remote

I would like something like

export const electron = window.require('electron').remote as ElectronType

so the IDE knows how to autocomplete the electron API.

@timsamart it does works. Thank you, it saves me days of work. 🤣

After spending many hours trying literally everything above, I missed the part in case you use BrowserView, just like BrowserWindow you need to explicitly enable node.js:

     new BrowserView({ // is a BrowserView not a BrowserWindow
        webPreferences: {
          nodeIntegration: true,
        },
      })
Was this page helpful?
0 / 5 - 0 ratings

Related issues

christiangenco picture christiangenco  ·  3Comments

diracdeltas picture diracdeltas  ·  3Comments

lealife picture lealife  ·  3Comments

wsangtoki picture wsangtoki  ·  3Comments

chonsser picture chonsser  ·  3Comments