Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Electron uses native modules


May 25, 2021 Electron


Table of contents


Electron also supports native modules, but since different V8 engines are used than the official Node, if you want to compile native modules, you need to manually set the location of Electron's headers.

Compatibility of native Node modules

When Node starts to replace the new version of the V8 engine, the native module may be "bad". T o make sure everything works, you need to check that the native module you want to use is supported by Node built into Electron. You can view the node version built into Electron here, or process.version (reference: Quick Start).

Considering that NAN can make your development easier to support multi-version Node, it is recommended that you use it to develop your own modules. You can also use NAN to port old modules to the new Nod e version so that they work well under the new Electron.

How to install the native module

There are three ways to teach you to install native modules:

The easiest way

The easiest way is to electron-rebuild package, which automatically helps you complete the steps of downloading the headers, compiling the native module, and so on:

npm install --save-dev electron-rebuild

# 每次运行"npm install"时,也运行这条命令
./node_modules/.bin/electron-rebuild

# 在windows下如果上述命令遇到了问题,尝试这个:
.\node_modules\.bin\electron-rebuild.cmd

Installed by npm

Of course you can also install native modules via npm Most of the steps are the same as when installing a normal module, except for some of the following system environment variables that you need to do yourself:

export npm_config_disturl=https://atom.io/download/atom-shell
export npm_config_target=0.33.1
export npm_config_arch=x64
export npm_config_runtime=electron
HOME=~/.electron-gyp npm install module-name

Installed via node-gyp

You need node-gyp where to download Electron's headers and what version to download:

$ cd /path-to-module/
$ HOME=~/.electron-gyp node-gyp rebuild --target=0.29.1 --arch=x64 --dist-url=https://atom.io/download/atom-shell

HOME=~/.electron-gyp where to find headers for development.

--target=0.29.1 the version of Electron

--dist-url=... Set the download address for Electron's headers

--arch=x64 the module to be compiled to fit the 64-bit operating system