完成项目
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||
const path = require('path');
|
||||
|
||||
// 动态导入 electron-store(ES 模块)
|
||||
let store;
|
||||
let storePromise = import('electron-store').then((StoreModule) => {
|
||||
const Store = StoreModule.default;
|
||||
store = new Store();
|
||||
return store;
|
||||
});
|
||||
|
||||
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;
|
||||
|
||||
let mainWindow;
|
||||
|
||||
function createWindow() {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1200,
|
||||
height: 800,
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
preload: path.join(__dirname, 'preload.cjs'),
|
||||
webSecurity: false, // 允许跨域请求(用于访问后端 API)
|
||||
},
|
||||
// icon: path.join(__dirname, '../assets/icon.png'), // 可选:应用图标(需要提供图标文件)
|
||||
});
|
||||
|
||||
// 加载应用
|
||||
if (isDev) {
|
||||
// 开发环境:加载 Vite 开发服务器
|
||||
mainWindow.loadURL('http://localhost:5173');
|
||||
mainWindow.webContents.openDevTools();
|
||||
} else {
|
||||
// 生产环境:加载打包后的文件
|
||||
const indexPath = path.join(__dirname, '../dist/index.html');
|
||||
mainWindow.loadFile(indexPath);
|
||||
}
|
||||
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
});
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
// 确保 store 已初始化
|
||||
await storePromise;
|
||||
|
||||
createWindow();
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// IPC 处理:获取/设置 API 地址
|
||||
ipcMain.handle('get-api-url', async () => {
|
||||
await storePromise;
|
||||
return store.get('apiUrl', 'http://192.168.1.148:7001');
|
||||
});
|
||||
|
||||
ipcMain.handle('set-api-url', async (event, url) => {
|
||||
await storePromise;
|
||||
store.set('apiUrl', url);
|
||||
return true;
|
||||
});
|
||||
|
||||
ipcMain.handle('get-ws-url', async () => {
|
||||
await storePromise;
|
||||
const apiUrl = store.get('apiUrl', 'http://192.168.1.148:7001');
|
||||
// 将 http:// 转换为 ws://, https:// 转换为 wss://
|
||||
return apiUrl.replace(/^http/, 'ws');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
const { contextBridge, ipcRenderer } = require('electron');
|
||||
|
||||
// 暴露受保护的方法给渲染进程
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
getApiUrl: () => ipcRenderer.invoke('get-api-url'),
|
||||
setApiUrl: (url) => ipcRenderer.invoke('set-api-url', url),
|
||||
getWsUrl: () => ipcRenderer.invoke('get-ws-url'),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user