先配置好将打包的web资源输出目录到新的目录

const path = require('path')
module.exports = {
  outputDir: path.resolve(__dirname, 'extraResources/dist'),
  productionSourceMap: false,
  // 添加全局变量
  pluginOptions: {
    electronBuilder: {
      builderOptions: {
        extraResources: ["./extraResources/**"],
      }
    },
  },
}

接下来需要做的是在打包好的dist资源上起一个http服务器

const express = require('express');
const path = require('path');
const app = express();
const os = require('os');

// 获取本机的局域网IP
function getServerIp() {
  let interfaces = os.networkInterfaces();
  for (let devName in interfaces) {
    let iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      let alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        console.log(alias.address);
        return alias.address;
      }
    }
  }
}

//创建服务器访问静态资源
function createHttpServer(win, port) {
  try {
    getServerIp();
    app.use('/', express.static(path.join(__dirname, 'extraResources/dist')));
    app.listen(port, () => {
      const ip = getServerIp();
      let url = `http://${ip}:${port}`;
			//告诉渲染进程访问地址,方便直接打开浏览器访问
      win.webContents.send('browserUrl', url);
    });
  } catch (error) {
    console.log(error);
  }
}

module.exports = {
  createHttpServer,
};

主进程中监听渲染进程是否需要进行ip访问

import { ipcMain } from 'electron';
const { createHttpServer } = require('./mainProcess/http-server');
let win;
async function createWindow() {
  win = new BrowserWindow({
    show: false,
    titleBarStyle: 'hidden',
    minWidth: 974,
    minHeight: 577,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, 'preload.js'),
      nativeWindowOpen: true,
    },
  });
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    // if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol('app');
    win.loadURL('app://./index.html');
  }
}
app.on('ready', async () => {
	createWindow();
})
ipcMain.on('openHttpServer', (e, data) => {
  createHttpServer(win, data); 
});

渲染进程控制是否开启,以及监听http服务链接

window?.ipcRenderer?.send('openHttpServer', window.ipConfig.webPort);
window?.ipcRenderer?.on('browserUrl', (e, data) => {
      console.log('访问地址:', data);
      //window?.ipcRenderer?.send('openInBrowser', data);
    });