1)下載了electron-rebuild 運行命令npm install --save-dev electron-rebuild
(2)下載node-gyp 運行命令npm install node-gyp -g
(3)下載sqlite3 運行命令npm install --save sqlite3
(4)在package.json中加入代碼 "rebuild": "electron-rebuild -f -w sqlite3"
(5)運行編譯:運行命令 npm run rebuild
意外出現報錯
(7)修改一下鏡像,運行代碼 npm install -g cnpm --registry=https://registry.npm.taobao.org
測試cnpm的是否安裝成功 運行命令cnpm -v
(8)清一下緩存npm cache clean -f (這一步很有必要!!!!!)
(9)緊接着運行命令 cnpm install sqlite3@latest --build-from-source --runtime=electron --target=8.3.0 --dist-url=https://atom.io/download/electron --save(--target=8.3.0注意要寫成自己下的electron的版本)
(9)執行第(6)步中的命令npm run rebuild
(10)將代碼放入渲染程序中(html中引入的js renderer.js文件中)
// This file is required by the index.html file and will // be executed in the renderer process for that window. // No Node.js APIs are available in this process because // `nodeIntegration` is turned off. Use `preload.js` to // selectively enable features needed in the rendering // process. // src/renderer/utils/db.js // 建表腳本,導出db對象供之后使用 let path = require('path'); let sq3 = require('sqlite3'); // import { docDir } from './settings'; // 將數據存至系統用戶目錄,防止用戶誤刪程序 const dbPath = path.join("D:\\huaxin\\elelctron\\electronTest\\electron-quick-start", 'data.sqlite'); const sqlite3 = sq3.verbose(); const db = new sqlite3.Database(dbPath); db.serialize(() => { db.run("create table test(name varchar(15))",function(){ db.run("insert into test values('hello,word')",function(){ db.all("select * from test",function(err,res){ if(!err){ console.log(JSON.stringify(res)); } else{ console.log(err); } }); }); }); });
當報錯require undefined時在main.js中引入nodeIntegration: true代碼放到webPreferences對象中
(11)然后運行npm start 會在console中看到輸出的代碼和再根目錄多一個.sqlite結尾的文件
文末附上認為比較好的文章連接
https://blog.csdn.net/zoepriselife316/article/details/89954383
https://www.cnblogs.com/alex96/p/12180296.html
也可以使用sql.js來代替sqlite3:https://www.cnblogs.com/alex96/p/12252992.html