mirror of
https://github.com/electron-vite/electron-vite-vue
synced 2025-08-26 15:01:18 +08:00
feat: support preload script hot reload
This commit is contained in:
@@ -2,7 +2,9 @@ import { watch, rollup, OutputOptions } from 'rollup'
|
||||
import minimist from 'minimist'
|
||||
import chalk from 'chalk'
|
||||
import ora from 'ora'
|
||||
import WebSocket from 'ws'
|
||||
import options from './rollup.config'
|
||||
import { createWsServer, formatWsSendData } from './ws'
|
||||
|
||||
const argv = minimist(process.argv.slice(2))
|
||||
const opt = options({ proc: 'preload', env: argv.env })
|
||||
@@ -12,13 +14,17 @@ const spinner = ora(`${TAG} Electron preload build...`)
|
||||
; (async () => {
|
||||
if (argv.watch) {
|
||||
const watcher = watch(opt)
|
||||
const wssObj = createWsServer({ TAG })
|
||||
|
||||
watcher.on('change', filename => {
|
||||
const log = chalk.yellow(`change -- ${filename}`)
|
||||
console.log(TAG, log)
|
||||
|
||||
/**
|
||||
* @todo Hot reload render process !!!
|
||||
*/
|
||||
// Hot reload renderer process !!!
|
||||
if (wssObj.instance?.readyState === WebSocket.OPEN) {
|
||||
console.log(TAG, 'Hot reload renderer process')
|
||||
wssObj.instance.send(formatWsSendData({ cmd: 'reload', data: Date.now() }))
|
||||
}
|
||||
})
|
||||
} else {
|
||||
spinner.start()
|
||||
|
43
script/ws.ts
Normal file
43
script/ws.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Hot reload from preload script during development
|
||||
*/
|
||||
import WebSocket from 'ws'
|
||||
import chalk from 'chalk'
|
||||
import pkg from '../package.json'
|
||||
|
||||
export interface CreateWsServerOptions {
|
||||
TAG: string
|
||||
}
|
||||
|
||||
export function createWsServer(options: CreateWsServerOptions) {
|
||||
const { TAG } = options
|
||||
const port = pkg.env.PORT_WS
|
||||
const host = '127.0.0.1'
|
||||
const wss = new WebSocket.Server({ host, port })
|
||||
const wssObj: { wss: WebSocket.Server; instance: WebSocket | null } = { wss, instance: null }
|
||||
|
||||
console.log(TAG, 'Wss run at - ' + chalk.yellow(`ws://${host}:${port}`))
|
||||
|
||||
wss.on('connection', ws => {
|
||||
console.log(TAG, chalk.yellow(`wss.on('connection')`))
|
||||
|
||||
wssObj.instance = ws
|
||||
ws.on('message', message => {
|
||||
console.log(TAG, `ws.on('message'):`, message.toString())
|
||||
})
|
||||
|
||||
ws.send(formatWsSendData({ cmd: 'message', data: 'connected.' }))
|
||||
})
|
||||
|
||||
wss.on('close', () => {
|
||||
console.log(TAG, chalk.gray(`wss.on('close')`))
|
||||
|
||||
wssObj.instance = null
|
||||
})
|
||||
|
||||
return wssObj
|
||||
}
|
||||
|
||||
export function formatWsSendData(json: { cmd: string, data?: any }) {
|
||||
return JSON.stringify(json)
|
||||
}
|
Reference in New Issue
Block a user