本节咱们学习如何在 Electron 中应用 Node 原生模块。

Electron 反对原生的 Node 模块,但因为和官网的 Node 相比,Electron 有可能应用一个和咱们零碎上所装置的 Node 不同的 V8 引擎,所以应用的模块须要从新编译能力应用。如果咱们想编译原生模块,则须要手动设置 Electronheaders 的地位。

如何装置原生模块

有三种装置原生模块的办法,别离是 :

  • Electron 装置并从新编译模块。
  • 通过 npm 装置原生模块。
  • Electron 手动编译。

为Electron装置并从新编译模块

最简略的形式就是通过 electron-rebuild 包为 Electron 重建模块,该模块能够主动确定 Electron 的版本,并解决下载 headers、为应用程序重建本机模块等步骤。

示例:

例如要通过 electron-rebuild 来重建模块,首先须要装置 electron-rebuild

npm install --save-dev electron-rebuild

每次运行 npm install 时,也会同时运行上面这条命令:

./node_modules/.bin/electron-rebuild

windows 下如果上述命令遇到了问题,能够尝试执行如下命令:

.\node_modules\.bin\electron-rebuild.cmd

通过npm装置

咱们还能够通过 npm 来间接装置原生模块。大部分步骤和装置一般模块时一样,然而须要本人设置一些零碎环境变量。

示例:

例如要装置所有 Electron 的依赖:

# Electron的版本export npm_config_target=1.2.3# Electron的指标架构export npm_config_arch=x64export npm_config_target_arch=x64# 下载Electron的headersexport npm_config_disturl=https://electronjs.org/headers# 通知node-pre-gyp咱们是在为Electron生成模块export npm_config_runtime=electron# 通知node-pre-gyp从源代码构建模块export npm_config_build_from_source=true# 装置所有依赖,并缓存到 ~/.electron-gypHOME=~/.electron-gyp npm install

为Electron手动编译

原生模块的开发人员如果想要在 Electron 中进行测试,可能要手动编译 Electron 模块。能够应用 node-gyp 来间接编译。

示例:

例如咱们要通知 node-gyp 去哪下载 Electronheaders,以及下载什么版本:

$ 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 :设置去哪找开发时的 headers
  • --target=0.29.1 :设置了 Electron 的版本。
  • --dist-url=... :设置了 Electronheaders 的下载地址。
  • --arch=x64 :设置了该模块为适配 64 位操作系统而编译。

链接:https://www.9xkd.com/