import type { PluginOption } from 'vite' import * as path from 'path' import * as fs from 'fs-extra' export interface ElectronBytecodeOptions { entry?: string keepSource?: boolean } export default function electronBytecode(options?: ElectronBytecodeOptions): PluginOption { return { name: 'vite-plugin-electron-encrypt', apply: 'build', async closeBundle() { if (process.env.NODE_ENV !== 'production') return const entryPath = path.resolve(process.cwd(), options?.entry || 'dist-electron/main/main.js'); if (!fs.pathExistsSync(entryPath)) return const outputPath = entryPath.replace(/\.js$/, '.jsc') const backupPath = `${entryPath}.bak` fs.copyFileSync(entryPath, backupPath) // We must compile the bytecode using the ELECTRON executable, not the local Node.js! // Node.js and Electron use different V8 versions. const electronPath = require('electron'); const { execFileSync } = require('child_process'); try { // Run a small script inside Electron to compile the file const compileScript = ` const bytenode = require('bytenode'); bytenode.compileFile({ filename: ${JSON.stringify(entryPath)}, output: ${JSON.stringify(outputPath)} }).then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); }); `; const tempScriptPath = path.join(path.dirname(entryPath), '_compile.js'); fs.writeFileSync(tempScriptPath, compileScript); execFileSync(electronPath, [tempScriptPath], { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } }); fs.unlinkSync(tempScriptPath); } catch (err) { console.error('Failed to compile bytecode with Electron:', err); throw err; } const stub = [ "require('bytenode')", `require('./${path.basename(outputPath)}')` ].join("\n") fs.writeFileSync(entryPath, stub) } } }