Home >Web Front-end >JS Tutorial >Why is \'require() is not defined\' in my Electron HTML page?

Why is \'require() is not defined\' in my Electron HTML page?

DDD
DDDOriginal
2024-11-01 18:18:30706browse

Why is

Electron: Resolving "require() is not defined" Error

When attempting to utilize Node.js functionalities within an Electron application's HTML pages, you may encounter an error stating that "require" is undefined. This arises due to a change in Electron introduced in version 5, where the default setting for nodeIntegration has been modified from true to false.

Solution:

To enable nodeIntegration, specify the following options when creating the Browser Window:

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

Example:

In the following code snippet, the app, dialog, and fs modules are being used within the HTML page:

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

  // Your code here...
</script></code>

By enabling nodeIntegration, you can seamlessly access Node.js functionality throughout your Electron application's HTML pages, allowing you to utilize the full range of Node.js capabilities in your Electron app.

The above is the detailed content of Why is \'require() is not defined\' in my Electron HTML page?. 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