electron.vite 项目创建以及better-sqlite3数据库使用
1.安装electron.vite
npm create @quick-start/electron@latest
中文官网:https://cn.electron-vite.org/
2. 安装项目依赖
npm i
3.修改 electron-builder 配置文件
appId: com.electron.app
productName: text33
directories:
buildResources: build
files:
- '!**/.vscode/*'
- '!src/*'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
asarUnpack:
- resources/**
win:
icon: build/icon.ico
# 配置文件示例,包含输入验证和异常处理逻辑
target:
-
target: "nsis" # 目标名称,必须为字符串
arch: ["x64"] # 架构列表,必须为非空列表
executableName: text33
nsis:
artifactName: ${name}-${version}-setup.${ext}
shortcutName: ${productName}
uninstallDisplayName: ${productName}
createDesktopShortcut: always
oneClick: false # 设置为 false 以提供安装类型选择界面,允许用户选择是否创建桌面图标,允许用户选择安装路径
perMachine: true # 设置为 true 将使安装程序默认为所有用户安装应用,这需要管理员权限
allowToChangeInstallationDirectory: true # 如果设置为 true,安装程序将允许用户更改安装目录
allowElevation: true # 一般情况下,此字段不会被直接使用,权限提升主要依赖于 perMachine 的设定。当perMachine为true,安装程序会请求管理员权限
deleteAppDataOnUninstall: true # 如果设置为 true,卸载程序将删除AppData中的所有程序数据
createStartMenuShortcut: true # 如果设置为 true,安装程序将在开始菜单中创建程序快捷方式
mac:
entitlementsInherit: build/entitlements.mac.plist
extendInfo:
- NSCameraUsageDescription: Application requests access to the device's camera.
- NSMicrophoneUsageDescription: Application requests access to the device's microphone.
- NSDocumentsFolderUsageDescription: Application requests access to the user's Documents folder.
- NSDownloadsFolderUsageDescription: Application requests access to the user's Downloads folder.
notarize: false
dmg:
artifactName: ${name}-${version}.${ext}
linux:
target:
- AppImage
- snap
- deb
maintainer: electronjs.org
category: Utility
appImage:
artifactName: ${name}-${version}.${ext}
npmRebuild: false
publish:
provider: generic
url: https://example.com/auto-updates
electronDownload:
mirror: https://npmmirror.com/mirrors/electron/
4.修改启动文件package.json
"scripts": {
"format": "prettier --write .",
"lint": "eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts,.vue --fix",
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
"typecheck:web": "vue-tsc --noEmit -p tsconfig.web.json --composite false",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
"start": "electron-vite preview",
"dev": "electron-vite dev",
"postinstall": "electron-builder install-app-deps",
"build": "npm run typecheck && electron-vite build",
"build:unpack": "npm run build && electron-builder --dir",
"build:win": "npm run build && electron-builder --win",
"build:mac": "npm run build && electron-builder --mac",
"build:linux": "npm run build && electron-builder --linux"
},
5.安装better-sqlite3数据库
npm i better-sqlite3 -S
数据库可视化 SQLiteStudio 下载地址 https://github.com/pawelsalawa/sqlitestudio/releases
better-sqlite3 https://www.npmjs.com/package/better-sqlite3
{
"scripts": {
"postinstall": "npx electron-rebuild -f",
"postinstall_backup": "electron-builder install-app-deps",
"rebuild-sqlite": "electron-rebuild -f -w better-sqlite3"
// ...
},
"dependencies": {
"@electron-toolkit/preload": "^3.0.1",
"@electron-toolkit/utils": "^3.0.0",
"better-sqlite3": "^11.8.1"
}
// ....
}
6.修改 electron-builder 配置文件
files:
- '!**/.vscode/*'
- '!src/*'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
- '!**/better-sqlite3/{deps/**/*,src/**/*}'
7.better-sqlite3使用
新建src/main/database/index.js文件
import Database from "better-sqlite3"; // 用于操作 SQLite 数据库的库
import { app, ipcMain } from "electron"; // 用于 Electron 应用的全局功能
import path from "path"; // 用于处理和操作文件路径的模块
import fs from "fs";
let db; // 声明一个变量用来存储数据库实例
// 数据库版本
const DB_VERSION = 1; // 当前数据库版本
// 初始化数据库的函数
export function initDatabase() {
// 判断当前环境是否是开发环境
let databasePath = path.join(app.getPath("userData"), "database");
console.log(databasePath);
// 确保数据库文件夹存在,如果不存在则创建它
if (!fs.existsSync(databasePath)) {
fs.mkdirSync(databasePath, { recursive: true });
}
// 初始化数据库并创建或打开指定路径的 SQLite 数据库文件
db = new Database(path.join(databasePath, "uploadfile.db"), {
verbose: console.log,
});
// 设置数据库的日志模式为 WAL(写时日志)模式,提高性能
db.pragma("journal_mode = WAL");
// 创建版本表
createVersionTable();
// 获取当前数据库版本
const currentVersion = getCurrentDatabaseVersion();
// 如果数据库版本不匹配,执行数据库更新
if (currentVersion !== DB_VERSION) {
updateDatabase(currentVersion);
}
// 创建表,如果表不存在则创建
createTable();
// 在 Electron 的主进程中注册一个 IPC 事件处理器
ipcMain.handle("db_query", async (_, query, params=[]) => {
const stmt = db.prepare(query); // 准备 SQL 查询
return stmt.all(...params); // 执行查询并返回结果
});
// 在应用退出时关闭数据库连接
app.on("quit", () => {
db.close(); // 关闭数据库连接
});
}
// 创建版本表
function createVersionTable() {
const createVersionTableQuery = `
CREATE TABLE IF NOT EXISTS version (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version INTEGER NOT NULL
);
`;
db.prepare(createVersionTableQuery).run();
// 检查是否有版本记录,若没有,则插入默认版本 1
const currentVersion = getCurrentDatabaseVersion();
if (!currentVersion) {
const insertVersionQuery = `INSERT INTO version (version) VALUES (?);`;
const stmt = db.prepare(insertVersionQuery);
stmt.run(1); // 默认插入版本 1
}
}
// 更新数据库
function updateDatabase(currentVersion) {
console.log(
`Updating database from version ${currentVersion} to ${DB_VERSION}`
);
if (currentVersion === 1) {
// 执行 1 -> 2 的更新操作
updateToVersion2();
}
// 更新数据库版本记录
const updateVersionQuery = `
INSERT INTO version (version) VALUES (?);
`;
const stmt = db.prepare(updateVersionQuery);
stmt.run(DB_VERSION);
console.log(`Database updated to version ${DB_VERSION}`);
}
// 创建任务列表表
function createTable() {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS todo_list (
user_id_role TEXT,
todo_id TEXT UNIQUE,
task_title TEXT,
task_description TEXT,
priority INTEGER,
due_date TEXT,
status TEXT,
created_at INTEGER,
updated_at INTEGER,
id INTEGER PRIMARY KEY AUTOINCREMENT
);
`;
// 执行创建表的 SQL 语句
db.prepare(createTableQuery).run();
}
@src/main/index.ts文件修改
import { initDatabase } from "./database/index";
// 在启动项目里面使用
app.whenReady().then(() => {
// 初始化数据库
ipcMain.on("initDatabase", () => {
// 初始化数据库
initDatabase();
});
}
页面可以直接调用
// 初始化数据库
const initDatabase = () => {
window.electron.ipcRenderer.send('initDatabase');
}
// 获取数据库中的所有待办事项
const getTodoList = () => {
// 获取数据库数据
window.ipcRenderer.invoke("db_query", "SELECT * FROM todo_list;").then((res)=>{
console.log('getTodoList', res);
getTodoListData.value = res;
}).catch((err)=>{
})
};
on对应send,不返回
handle对应invoke,返回
8.多窗口使用
// 创建新窗口
ipcMain.on('create-new-window', () => {
if (newWindow) {
// 是否是最小化
if (newWindow.isMinimized()) {
newWindow.restore()
};
newWindow.focus() // 存在 则聚焦
return
}
newWindow = new BrowserWindow({
width: 312,
height: 422,
show: false,
autoHideMenuBar: true,
...(process.platform === "linux" ? { icon } : {}),
webPreferences: {
preload: join(__dirname, "../preload/about.js"),
sandbox: false,
},
});
newWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url);
return { action: "deny" };
});
newWindow.on("ready-to-show", () => {
newWindow.show();
});
// 关闭清理
newWindow.on('closed', () => {
newWindow = null
});
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
console.log(
"process.env['ELECTRON_RENDERER_URL']",
process.env["ELECTRON_RENDERER_URL"] + "/about.html"
);
newWindow.loadURL(process.env["ELECTRON_RENDERER_URL"] + "/about.html");
} else {
newWindow.loadFile(join(__dirname, "../renderer/about.html"));
}
});
…/preload/about.js 文件内容
import { contextBridge } from "electron";
import { electronAPI } from "@electron-toolkit/preload";
// Custom APIs for renderer
const api = {};
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld("electron", electronAPI);
contextBridge.exposeInMainWorld("api", api);
} catch (error) {
console.error(error);
}
} else {
// @ts-ignore (define in dts)
window.electron = electronAPI
// @ts-ignore (define in dts)
window.api = api
}
遇到问题
mac在打包win,安装完成会出现以下错误属于系统编辑问题,请使用win系统进行对应打包
npm i 安装不上,网络正常情况
npm config set registry https://registry.npmmirror.com
淘宝镜像可能会出现问题
win在打包是否出现的权限问题需要开启管理员权限
如遇到其他问题可以沟通