返回

Apple M1 Mac 上 Electron 中的 SQLite3:揭秘其强大的编译安装过程

前端

在 Apple M1 Mac 上为 Electron 集成 SQLite3 的详细指南

先决条件

  • 安装 Node.js 12 或更高版本
  • 安装 npm 6 或更高版本
  • 安装 XCode 12 或更高版本

编译 SQLite3

  1. 克隆 SQLite3 存储库:
git clone https://github.com/sqlite/sqlite.git
  1. 切换到 SQLite3 目录:
cd sqlite
  1. 配置 SQLite3:
./configure --enable-fts5 --enable-json1 --enable-session --enable-spatialite --enable-tempstore
  1. 编译 SQLite3:
make
  1. 安装 SQLite3:
make install

编译 Electron-SQLite3 模块

  1. 创建 Electron-SQLite3 项目:
mkdir electron-sqlite3
cd electron-sqlite3
npm init -y
  1. 安装依赖项:
npm install electron electron-rebuild sqlite3 --save-dev
  1. 创建 bindings.gyp 文件:
{
  "targets": [
    {
      "target_name": "electron-sqlite3",
      "sources": [ "electron-sqlite3.cc" ],
      "include_dirs": [
        "/usr/local/include",
        "node_modules/sqlite3/include"
      ],
      "libraries": [
        "-lsqlite3"
      ],
      "conditions": [
        ['OS=="darwin"', {
          "libraries": [
            "-framework",
            "Carbon",
            "-framework",
            "CoreFoundation"
          ]
        }]
      ]
    }
  ]
}
  1. 创建 electron-sqlite3.cc 文件:
#include <node.h>
#include <sqlite3.h>

namespace demo {

using v8::FunctionCallbackInfo<v8::Value>;
using v8::Isolate;
using v8::Local<v8::Context>;
using v8::Local<v8::Function>;
using v8::Local<v8::Object>;
using v8::Local<v8::String>;
using v8::MaybeLocal<v8::Object>;
using v8::MaybeLocal<v8::Value>;
using v8::ObjectTemplate;
using v8::String::Utf8Value;

void Init(Local<Object> exports, Local<Context> context) {
  // ...
}

NODE_MODULE(electron-sqlite3, Init)

}  // namespace demo
  1. 构建 Electron-SQLite3 模块:
npm run electron-rebuild

使用 SQLite3 模块

在 Electron 应用程序中使用 SQLite3 模块非常简单:

const sqlite3 = require('electron-sqlite3').sqlite3;

const db = new sqlite3.Database(':memory:');

db.run('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
db.run('INSERT INTO users (name) VALUES (?)', ['John Doe']);

db.each('SELECT * FROM users', (err, row) => {
  console.log(row);
});

db.close();

常见问题解答

1. 为什么需要在 Apple M1 Mac 上进行特殊编译?

Apple M1 Mac 具有独特的 ARM64 架构,因此需要专门针对此架构编译 SQLite3。

2. bindings.gyp 文件中的 "conditions" 部分是什么意思?

"conditions" 部分指定了在特定条件下构建模块所需的额外编译标志。在这种情况下,它指定了在 Mac 上构建时所需的其他库。

3. electron-sqlite3.cc 文件中的 "namespace demo" 是做什么用的?

"namespace demo" 将模块中的所有函数和变量封装在一个名为 "demo" 的命名空间中,以避免与其他模块中的符号冲突。

4. 如何在应用程序中导入 SQLite3 模块?

使用 require() 方法导入模块:const sqlite3 = require('electron-sqlite3').sqlite3;

5. 如何使用 SQLite3 模块连接到数据库?

使用 new sqlite3.Database() 构造函数:const db = new sqlite3.Database(':memory:');