使用 Node 原生模块

    如下三种方法教你安装原生模块

    只要设置一些系统环境变量,你就可以通过 直接安装原生模块。

    为 Electron 安装所有依赖项的一个例子:

    你可以也选择安装其他 Node 项目模块一样,然后用 electron-rebuild 包重建 Electron 模块 。 它可以识别当前 Electron 版本,帮你自动完成了下载 headers、编译原生模块等步骤。

    一个下载 electron-rebuild 并重新编译的例子:

    HOME=~/.electron-gyp 设置去哪找开发时的 headers。 —target=1.2.3 设置了 Electron 的版本。 —dist-url=…设置了 Electron 的 headers 的下载地址。 —arch=x64 设置了该模块为适配64位操作系统而编译。

    针对与公共发行版不匹配的Electron的自定义版本编译原生Node插件,npm要使用与自定义版本对应的Node版本。

    如果你安装了一个原生模块并发现它不能工作,你需要检查 以下事项:

    • win_delay_load_hook is not set to false in the module's binding.gyp.
    • 如果升级了 Electron,你通常需要重新编译这些模块。
    • 当有疑问时,请先执行 electron-rebuild

    On Windows, by default, node-gyp links native modules against . However, in Electron 4.x and higher, the symbols needed by native modules are exported by electron.exe, and there is no node.dll in Electron 4.x. In order to load native modules on Windows, node-gyp installs a that triggers when the native module is loaded, and redirects the node.dll reference to use the loading executable instead of looking for node.dll in the library search path (which would turn up nothing). As such, on Electron 4.x and higher, 'win_delay_load_hook': 'true' is required to load native modules.

    If you get an error like Module did not self-register, or The specified procedure could not be found, it may mean that the module you're trying to use did not correctly include the delay-load hook. If the module is built with node-gyp, ensure that the win_delay_load_hook variable is set to true in the binding.gyp file, and isn't getting overridden anywhere. If the module is built with another system, you'll need to ensure that you build with a delay-load hook installed in the main .node file. Your invocation should look like this:

    • you link against node.lib from Electron and not Node. If you link against the wrong node.lib you will get load-time errors when you require the module in Electron.
    • win_delay_load_hook.obj is linked directly into the final DLL. If the hook is set up in a dependent DLL, it won't fire at the right time.
      See node-gyp for an example delay-load hook if you're implementing your own.

    为多个版本的 Node 和 Electron 提供了一种简单发布预编译二进制原生模块的方法。

    如果为 Electron 提供二进制原生模块,请确保删除 —build-from-sourcenpm_config_build_from_source 环境变量 来充分利用预编译的二进制文件。

    node-pre-gyp 工具 提供一种部署原生 Node 预编译二进制模块的方法, 许多流行的模块都是使用它。

    通常这些模块在 Electron 中工作良好,但有时当 Electron 使用 比 Node 新的 V8 版本时,会有 ABI 改变,可能发生错误。 因此,一般来说,建议始终从源代码编译原生模块。

    如果你通过 npm 的方式安装模块,默认情况下这就完成了, 如果没有,你需要传入 —build-from-source 给 , 或者设置 npm_config_build_from_source 环境变量。