In Electron, using node_modules involves the following steps:
1. Install the required npm packages
First, install the required npm packages for your Electron project. This can be done by running npm or yarn installation commands. For example, if you need to install lodash, run the following command in the terminal at the project root directory:
bashnpm install lodash
Or using yarn:
bashyarn add lodash
2. Use modules in Electron's main process or renderer process
Main process
In Electron's main process, you can directly use require to access the installed modules, as the main process supports Node.js API. For example:
javascriptconst { app, BrowserWindow } = require('electron'); const lodash = require('lodash'); // Use lodash for operations console.log(lodash.shuffle([1, 2, 3, 4]));
Renderer process
In the renderer process, due to security considerations, Node.js integration is disabled by default. If you want to use Node.js modules in the renderer process, enable nodeIntegration when creating BrowserWindow:
javascriptconst win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } });
Then, in the renderer process file, you can use require to access modules as in the main process:
javascriptconst lodash = require('lodash'); console.log(lodash.shuffle([1, 2, 3, 4]));
3. Consider security
Since enabling nodeIntegration may introduce security risks, it is recommended not to enable it directly in the renderer process if possible. If you need to use Node.js features in the renderer process, consider using contextBridge and preload scripts to expose only necessary functionalities to the renderer process.
For example, you can safely expose lodash methods in the preload script:
javascriptconst { contextBridge } = require('electron'); const lodash = require('lodash'); contextBridge.exposeInMainWorld('myAPI', { shuffle: (array) => lodash.shuffle(array) });
Then, in the renderer process, you can access these methods via the global variable window.myAPI:
javascriptconsole.log(window.myAPI.shuffle([1, 2, 3, 4]));
By following these steps, you can effectively and securely use node_modules in your Electron project. This ensures both functionality and security.