前言
本人用的是Apple M1芯片的电脑,最近在做一个基于electron开发的桌面客户端,数据库使用的是sqlite3,但node环境下安装的sqlite3在electron环境中无法使用,需要重新编译,而且npm镜像上没有编译好的arm64版本的sqlite3😨😓😭
没办法,只能自己手动编译了,经过一番摸索折腾,终于成功编译出electron环境中可以使用的sqlite3,自己动手,丰衣足食😁😃😆
编译环境
- macOS 11.5.2(Apple M1芯片)
- node 16.14.0(arm64)
- electron 16.0.6
- node-gyp 8.4.1
准备工作
全局安装electron
npm install electron@16.0.6 -g
全局安装node-gyp
npm install node-gyp -g
编译安装sqlite3模块
请确保本机安装的是arm64版本的node,下载地址:nodejs.org/en/download
- 下载sqlite3模块
npm install sqlite3 --ignore-scripts
之所以加上 --ignore-scripts,是因为sqlite3模块在package.json文件中写了下载时自动执行编译的脚本,如下:
"scripts": {
"install": "node-pre-gyp install --fallback-to-build",
......
}
往往这时候我们的编译环境还没准备好,如果编译失败了,会导致整个包都下载不下来。
- 手动执行脚本进行编译
cd node_modules/sqlite3
node-gyp rebuild --target=16.0.6 --arch=arm64 --dist-url=https://electronjs.org/headers --module_name=node_sqlite3 --module_path=../lib/binding/napi-v3-darwin-arm64
--target=16.0.6 //指定electron版本为16.0.6
--arch=arm64 //指定编译架构为arm64
--dist-url=xxx //相关依赖下载地址
--module_name=node_sqlite3 //指定模块名称为node_sqlite3
--module_path=../lib/binding/napi-v3-darwin-arm64 //编译输出路径
如编译出现错误信息:
libtool: unrecognized option -static
,则执行以下命令:
export PATH=/Library/Developer/CommandLineTools/usr/bin:$PATH
验证sqlite3
const sqlite3=require('sqlite3')
let db = new sqlite3.Database('sq3.db', (err) => {
if (err) {
return console.error(err.message);
}
console.log('已经成功连接SQLite数据库');
});
一个完整的可运行的electron demo已经上传GitHub,地址:github.com/kongpf8848/…