在 Electron 中使用 NodeJS 插件

2022-01-10 00:00:00 node.js electron sqlite

我是 Electron (Atom-shell) 的新手,我正在尝试将 NodeJS 插件加载到我正在构建的应用程序中,但我不知道如何操作.文档对此并不清楚.

I am new to Electron (Atom-shell), and I am trying to load a NodeJS plugin into the application I am building, but I don't know how. The documentation is not clear on that.

例如,我尝试在我的应用程序中使用 sqlite3 插件,我使用了 npm install sqlite3,它已成功安装.但是当我尝试调用它 var sqlite = require('sqlite3') 时,应用程序会抛出错误.是否还有其他我不知道的步骤?

For instance, I am trying to use sqlite3 plugin in my app, I used npm install sqlite3, and it was successfully installed. But the application throws and error when I try to call it var sqlite = require('sqlite3'). Are there any further steps I am not aware of ?

谢谢.

推荐答案

对于纯 JS(即非原生)模块,您需要以下内容:

For pure JS (i.e. not native) modules you need the following:

  1. 将模块列在您的 package.json 依赖项中
  2. 让 electron 知道在哪里可以找到模块(例如 export NODE_PATH=/PATH/TO/node_module)
  1. Have the module listed in your package.json dependencies
  2. Let electron know where to find the module (e.g. export NODE_PATH=/PATH/TO/node_module)

第一个要求很明显,第二个要求源于this issue.

The first requirement is obvious and the second has its roots in this issue.

对于使用 C++ 绑定的本机节点模块(例如 sqlite3),您需要针对电子标头构建它们才能工作.根据 电子文档,最简单的方法是:

For native node modules (such as sqlite3) which use C++ bindings, you need to build them against electron headers to work. According to electron docs, the easiest way to do that would be:

npm install --save-dev electron-rebuild

# Every time you run npm install, run this
./node_modules/.bin/electron-rebuild

相关文章