electron-vite-vue/scripts/build-preload.ts

50 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-11-09 09:01:52 +08:00
import { watch, rollup, OutputOptions, Plugin } from 'rollup'
2021-08-05 09:25:34 +08:00
import minimist from 'minimist'
import chalk from 'chalk'
2021-09-09 09:35:21 +08:00
import ora from 'ora'
import WebSocket from 'ws'
2021-09-09 09:35:21 +08:00
import options from './rollup.config'
2021-11-09 09:01:52 +08:00
import { createWsServer, formatWsSendData, WssServer } from './ws'
2021-08-05 09:25:34 +08:00
const argv = minimist(process.argv.slice(2))
2021-11-09 09:01:52 +08:00
const opts = options({ proc: 'preload', env: argv.env })
2021-08-05 09:25:34 +08:00
const TAG = '[build-preload.ts]'
2021-09-09 09:35:21 +08:00
const spinner = ora(`${TAG} Electron preload build...`)
2021-08-05 09:25:34 +08:00
2021-11-09 09:01:52 +08:00
function hotReloadPreload(wssServer: WssServer): Plugin {
return {
name: 'hot-reload-preload',
writeBundle() {
// Hot reload preload script !!!
if (wssServer.instance?.readyState === WebSocket.OPEN) {
console.log(TAG, 'Hot reload preload script')
wssServer.instance.send(formatWsSendData({ cmd: 'reload', data: Date.now() }))
}
},
}
}
2021-09-09 09:35:21 +08:00
; (async () => {
if (argv.watch) {
2021-11-09 09:01:52 +08:00
const wssServer = createWsServer()
opts.plugins = opts.plugins?.concat(hotReloadPreload(wssServer))
const watcher = watch(opts)
2021-09-09 09:35:21 +08:00
watcher.on('change', filename => {
2021-11-09 09:01:52 +08:00
console.log(TAG, chalk.yellow(`change -- ${filename}`))
2021-08-05 09:25:34 +08:00
})
2021-09-09 09:35:21 +08:00
} else {
spinner.start()
try {
2021-11-09 09:01:52 +08:00
const build = await rollup(opts)
await build.write(opts.output as OutputOptions)
2021-09-09 09:35:21 +08:00
spinner.succeed()
process.exit()
} catch (error) {
2021-08-05 09:25:34 +08:00
console.log(`\n${TAG} ${chalk.red('构建报错')}\n`, error, '\n')
2021-09-09 09:35:21 +08:00
spinner.fail()
process.exit(1)
}
2021-08-05 09:25:34 +08:00
}
2021-09-09 09:35:21 +08:00
})();