如何让Electron应用托管本地网络可访问的网站?
可行方案:用Electron主进程托管静态网站(整合Express API)
步骤1:配置Client端Vite构建路径
修改client目录下的vite.config.js,将构建产物输出到Electron项目的统一dist目录,方便后续打包:
// client/vite.config.js import { defineConfig } from 'vite'; export default defineConfig({ build: { outDir: '../dist/client', // 输出到根目录的dist/client emptyOutDir: true, }, });
步骤2:主进程整合Express API与静态网站托管
在Electron主进程中,用Express同时处理原有API请求和静态网站的托管,区分开发/生产环境路径:
// main/index.js const { app } = require('electron'); const express = require('express'); const path = require('path'); const expressApp = express(); // 处理原有API路由 expressApp.get('/api/stream-deck/status', (req, res) => { res.json({ online: true, devices: [] }); }); // 托管静态网站 if (app.isPackaged) { // 生产环境:指向打包后的client静态文件 const staticDir = path.join(app.getAppPath(), 'dist/client'); expressApp.use(express.static(staticDir)); // SPA路由兼容:刷新页面时返回index.html expressApp.get('*', (req, res) => { res.sendFile(path.join(staticDir, 'index.html')); }); } else { // 开发环境:反向代理到client的Vite开发服务器,避免频繁构建 const { createProxyMiddleware } = require('http-proxy-middleware'); expressApp.use('/*', createProxyMiddleware({ target: 'http://localhost:5173', // 替换为client的dev服务端口 changeOrigin: true, })); } // 启动服务器,监听本地网络可访问的端口 const server = expressApp.listen(3000, '0.0.0.0', () => { console.log(`服务运行在:http://localhost:3000`); }); // 关闭Electron时终止服务器 app.on('before-quit', () => server.close());
步骤3:配置electron-vite打包规则
修改根目录的electron-vite.config.js,确保client的构建产物被包含到最终的.exe包中:
// electron-vite.config.js import { defineConfig } from 'electron-vite'; export default defineConfig({ main: { build: { outDir: 'dist/main', rollupOptions: { external: ['express'], // 依赖不打包进主进程,用系统node_modules }, }, }, renderer: { build: { outDir: 'dist/renderer', }, }, build: { outDir: 'dist', files: [ 'dist/main/**/*', 'dist/renderer/**/*', 'dist/client/**/*', // 强制包含client的静态文件 ], }, });
步骤4:开发与打包流程
开发阶段:
- 启动client的开发服务:
cd client && npm run dev - 启动Electron应用:
npm run dev
此时访问http://localhost:3000就能看到client网站,API请求正常转发。
- 启动client的开发服务:
打包阶段:
- 构建client:
cd client && npm run build - 打包Electron应用:
npm run build
生成的.exe包包含所有资源,启动后局域网内设备可通过你的电脑IP:3000访问网站。
- 构建client:
注意事项
- 服务器必须监听
0.0.0.0而非localhost,否则局域网设备无法访问。 - 生产环境可根据需求调整端口号,避免与其他服务冲突。
内容的提问来源于stack exchange,提问作者Gustavo Luz
相关产品推荐
相关产品推荐

