48 lines
1.7 KiB
TypeScript
48 lines
1.7 KiB
TypeScript
// 开发环境的插件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地址
|
||
let electronProcess = spawn(require('electron'), ['dist/background.js', IP])
|
||
fs.watchFile('src/background.ts', ()=>{
|
||
console.log('提示', 'background.ts 文件发生改变,electronProcess 重新启动')
|
||
electronProcess.kill()
|
||
BuildBackground()
|
||
electronProcess = spawn(require('electron'), ['dist/background.js', IP])
|
||
})
|
||
electronProcess.stderr.on('data', (data) => {
|
||
console.log('日志', data.toString())
|
||
})
|
||
|
||
})
|
||
}
|
||
}
|
||
} |