Home  >  Article  >  Web Front-end  >  Why is \'require()\' undefined in Electron and How Do I Fix It?

Why is \'require()\' undefined in Electron and How Do I Fix It?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 11:21:02187browse

Why is 'require()' undefined in Electron and How Do I Fix It?

Electron 'require()' undefined: Enabling Node Access in HTML

In Electron, if you encounter the error "require() is not defined" when attempting to utilize Node.js functionality within HTML pages, it signifies that Node integration is disabled by default since Electron version 5. To resolve this issue, you must explicitly enable nodeIntegration for each BrowserWindow.

To activate Node integration, modify the BrowserWindow creation code as follows:

<code class="js">app.on('ready', () => {
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        }
    });
});</code>

By setting nodeIntegration to true and contextIsolation to false, you allow direct access to Node.js modules, enabling you to utilize variables such as:

<code class="js">var app = require('electron').remote; 
var dialog = app.dialog;
var fs = require('fs');</code>

within your HTML pages and any Electron windows. This allows you to leverage Node.js functionalities seamlessly throughout your Electron application.

The above is the detailed content of Why is \'require()\' undefined in Electron and How Do I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn