electron-app-c1-launcher/plugins/vite.electron.dev.ts

48 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-09-22 15:07:40 +00:00
// 开发环境的插件electron
import type { Plugin } from 'vite'
import type { AddressInfo } from 'node:net'
import { spawn } from 'node:child_process'
import fs from 'node:fs'
const BuildBackground = ()=>{
// 要使用require,需要 在package.json中把type:module删除
// 编译ts脚本为js
require('esbuild').buildSync({
entryPoints: ['src/background.ts'],
bundle: true,
outfile: 'dist/background.js',
platform: 'node',
target: 'node12',
external:['electron']
})
}
// vite 插件要求必须要返回一个有name属性的对象
// 这个对象有很多钩子
export const ElectronDevPlugin = (): Plugin => {
return {
name: 'electron-dev',
configureServer(server){
BuildBackground()
server?.httpServer?.on('listening', () =>{
// 读取vite服务信息
const addressInfo = server.httpServer?.address() as AddressInfo
// 拼接ip地址
const IP = `http://localhost:${addressInfo.port}`
// 进程传参发给electron IP地址
2024-09-22 16:26:29 +00:00
let electronProcess = spawn(require('electron'), ['dist/background.js', IP])
2024-09-22 15:07:40 +00:00
fs.watchFile('src/background.ts', ()=>{
2024-09-22 16:26:29 +00:00
console.log('提示', 'background.ts 文件发生改变electronProcess 重新启动')
electronProcess.kill()
2024-09-22 15:07:40 +00:00
BuildBackground()
2024-09-22 16:26:29 +00:00
electronProcess = spawn(require('electron'), ['dist/background.js', IP])
2024-09-22 15:07:40 +00:00
})
2024-09-22 16:26:29 +00:00
electronProcess.stderr.on('data', (data) => {
2024-09-22 15:07:40 +00:00
console.log('日志', data.toString())
})
})
}
}
}