electron-vite-vue/scripts/watch.mjs

73 lines
1.7 KiB
JavaScript
Raw Normal View History

process.env.NODE_ENV = 'development'
2021-11-11 17:52:50 +08:00
2022-01-27 10:48:32 +08:00
import { fileURLToPath } from 'url'
import { join, dirname } from 'path'
import { createRequire } from 'module'
2022-01-27 10:48:32 +08:00
import { spawn } from 'child_process'
import { createServer, build } from 'vite'
import electron from 'electron'
2021-11-11 17:52:50 +08:00
2022-01-27 10:48:32 +08:00
const __dirname = dirname(fileURLToPath(import.meta.url))
const require = createRequire(import.meta.url)
const pkg = require('../package.json')
2021-11-11 17:52:50 +08:00
/**
2022-01-27 10:48:32 +08:00
* @type {() => Promise<import('rollup').RollupWatcher>}
2021-11-11 17:52:50 +08:00
*/
2022-01-27 10:48:32 +08:00
function watchMain() {
2021-11-11 17:52:50 +08:00
/**
* @type {import('child_process').ChildProcessWithoutNullStreams | null}
*/
let electronProcess = null
2022-01-27 10:48:32 +08:00
return build({
configFile: 'scripts/vite.config.mjs',
root: join(__dirname, '../src/main'),
build: {
outDir: '../../dist/main',
2022-01-30 11:13:30 +08:00
watch: true,
2021-11-11 17:52:50 +08:00
},
2022-01-27 10:48:32 +08:00
plugins: [{
name: 'electron-main-watcher',
writeBundle() {
electronProcess && electronProcess.kill()
electronProcess = spawn(electron, ['.'], {
stdio: 'inherit',
env: Object.assign(process.env, pkg.env),
})
},
}],
2021-11-11 17:52:50 +08:00
})
}
/**
2022-01-27 10:48:32 +08:00
* @type {(server: import('vite').ViteDevServer) => Promise<import('rollup').RollupWatcher>}
2021-11-11 17:52:50 +08:00
*/
2022-01-27 10:48:32 +08:00
function watchPreload(server) {
return build({
configFile: 'scripts/vite.config.mjs',
root: join(__dirname, '../src/preload'),
build: {
outDir: '../../dist/preload',
2022-01-30 11:13:30 +08:00
watch: true,
2021-11-11 17:52:50 +08:00
},
2022-01-27 10:48:32 +08:00
plugins: [{
name: 'electron-preload-watcher',
writeBundle() {
server.ws.send({ type: 'full-reload' })
},
}],
2021-11-11 17:52:50 +08:00
})
}
// bootstrap
2022-01-27 10:48:32 +08:00
const server = await createServer({ configFile: 'src/renderer/vite.config.ts' })
2021-11-11 17:52:50 +08:00
2022-01-27 10:48:32 +08:00
await server.listen()
2022-01-30 08:27:44 +08:00
console.log() // for beautiful log.
2022-01-27 10:48:32 +08:00
await watchPreload(server)
2022-01-30 08:27:44 +08:00
console.log()
2021-11-11 17:52:50 +08:00
await watchMain()