To use native Node modules in your packaged Electron application, you'll need to follow these steps:
First, install the native Node module using npm, just like you would in any other Node.js project:
npm install <module-name>
Since Electron uses a different Node.js version and ABI (Application Binary Interface) than the one installed on your system, you'll need to rebuild the native module for Electron. You can use the electron-rebuild
package to automate this process.
Install electron-rebuild
as a dev dependency:
npm install --save-dev electron-rebuild
Then, rebuild the native modules:
./node_modules/.bin/electron-rebuild
On Windows, you might need to use:
.\node_modules\.bin\electron-rebuild.cmd
Alternatively, you can set up environment variables to install and rebuild native modules directly using npm. Here's an example:
# Set Electron's version
export npm_config_target=1.2.3
# Set the architecture of your machine
export npm_config_arch=x64
# Set the target architecture
export npm_config_target_arch=x64
# Set the distribution URL for Electron headers
export npm_config_disturl=https://electronjs.org/headers
# Tell node-pre-gyp to build the module from source code
export npm_config_runtime=electron
export npm_config_build_from_source=true
# Install all dependencies
HOME=~/.electron-gyp npm install
If you prefer to manually rebuild the native module, you can use node-gyp
. Navigate to the module's directory and run:
cd /path-to-module/
HOME=~/.electron-gyp node-gyp rebuild --target=1.2.3 --arch=x64 --dist-url=https://electronjs.org/headers
For larger projects, it's a good practice to separate frontend and backend dependencies. You can have two package.json
files: one for frontend dependencies and one for backend (native) dependencies.
Root package.json
:
{
"name": "my-app",
"version": "1.0.0",
"description": "A sample application",
"license": "Apache-2.0",
"main": "./src/main/main.mjs",
"dependencies": {
"react": "^18.2.0",
"react-router-dom": "^5.3.3"
},
"devDependencies": {
"electron": "^31.2.1",
"electron-builder": "^25.0.1"
}
}
Backend package.json
:
{
"name": "my-app",
"version": "1.0.0",
"description": "A sample application",
"license": "Apache-2.0",
"main": "./dist/main/main.js",
"scripts": {
"postinstall": "./node_modules/.bin/electron-rebuild"
},
"dependencies": {
"sqlite3": "^5.1.7",
"sharp": "^0.33.5"
}
}
By following these steps, you can successfully use native Node modules in your Electron application. This ensures compatibility and stability across different platforms.
Does this help, or do you have any specific questions about using native Node modules in Electron?