WebMusic/webapp/electron/main.cjs

83 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
// 动态导入 electron-storeES 模块)
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');
});