electron-jue-jin/plugins/devPlugin.ts

61 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

2024-04-05 15:06:50 +00:00
import { Plugin, ViteDevServer } from 'vite'
export let devPlugin = () => {
return {
name: "dev-plugin",
configureServer(server: ViteDevServer) {
import('esbuild').then(instance => {
instance.buildSync({
entryPoints: ["./src/main/mainEntry.ts"],
bundle: true,
platform: 'node',
outfile: "./dist/mainEntry.js",
external: ["electron"]
})
})
server.httpServer?.once("listening", () => {
import("child_process").then(({ spawn }) => {
let addressInfo = server.httpServer?.address() as { address: string; port: number }
if (addressInfo) {
let httpAddress = `http://${addressInfo.address}:${addressInfo.port}`
import('electron').then(electron => {
let electronProcess = spawn('electron', ['./dist/mainEntry.js', httpAddress], {
cwd: process.cwd(),
stdio: "inherit",
shell: true
})
electronProcess.on("close", () => {
server.close()
process.exit()
})
})
}
})
})
}
}
}
export const getReplacer = () => {
const externalModels = ["os", "fs", "path", "events", "child_process",
"crypto", "http", "buffer", "url", "better-sqlite3", "knex"
]
const result: Record<string, () => { find: RegExp, code: string }> = {}
for (const item of externalModels) {
result[item] = () => ({
find: new RegExp(`^${item}$`),
code: `const ${item} = require('${item}'); export { ${item} as default }`
})
}
result['electron'] = () => {
const electronModules = ["clipboard", "ipcRenderer", "nativeImage",
"shell", "webFrame"
].join(",")
return {
find: new RegExp(`^electron$`),
code: `const {${electronModules}} = require('electron'); export { ${electronModules} }`
}
}
return result
}