|
| 1 | +import { |
| 2 | + type Plugin, |
| 3 | + type UserConfig, |
| 4 | + mergeConfig, |
| 5 | +} from 'vite' |
| 6 | +import type { InputOption } from 'rollup' |
| 7 | +import electron, { type ElectronOptions } from '.' |
| 8 | + |
| 9 | +export interface ElectronSimpleOptions { |
| 10 | + main: ElectronOptions |
| 11 | + preload?: Omit<ElectronOptions, 'entry'> & { |
| 12 | + /** |
| 13 | + * Shortcut of `build.rollupOptions.input`. |
| 14 | + * |
| 15 | + * Preload scripts perhaps bundle as web format, so use the `build.rollupOptions.input` instead `build.lib.entry`. |
| 16 | + */ |
| 17 | + input: InputOption |
| 18 | + } |
| 19 | + /** |
| 20 | + * Support use Node.js API in Electron-Renderer |
| 21 | + * @see https://github.com/electron-vite/vite-plugin-electron-renderer |
| 22 | + */ |
| 23 | + renderer?: import('vite-plugin-electron-renderer').RendererOptions |
| 24 | +} |
| 25 | + |
| 26 | +// Vite v3.x support async plugin. |
| 27 | +export default async function electronSimple(options: ElectronSimpleOptions): Promise<Plugin[]> { |
| 28 | + const opts = [options.main] |
| 29 | + if (options.preload) { |
| 30 | + const { |
| 31 | + input, |
| 32 | + vite: viteConfig = {}, |
| 33 | + ...preloadOptions |
| 34 | + } = options.preload |
| 35 | + const preload: ElectronOptions = { |
| 36 | + onstart(args) { |
| 37 | + // Notify the Renderer-Process to reload the page when the Preload-Scripts build is complete, |
| 38 | + // instead of restarting the entire Electron App. |
| 39 | + args.reload() |
| 40 | + }, |
| 41 | + ...preloadOptions, |
| 42 | + vite: mergeConfig({ |
| 43 | + build: { |
| 44 | + rollupOptions: { |
| 45 | + input, |
| 46 | + output: { |
| 47 | + // Only one file will be bundled, which is consistent with the behavior of `build.lib` |
| 48 | + manualChunks: {}, |
| 49 | + // https://github.com/vitejs/vite/blob/v4.4.9/packages/vite/src/node/build.ts#L604 |
| 50 | + entryFileNames: '[name].js', |
| 51 | + chunkFileNames: '[name].js', |
| 52 | + assetFileNames: '[name].[ext]', |
| 53 | + }, |
| 54 | + }, |
| 55 | + } as UserConfig, |
| 56 | + }, viteConfig), |
| 57 | + } |
| 58 | + opts.push(preload) |
| 59 | + } |
| 60 | + const plugins = electron(opts) |
| 61 | + |
| 62 | + if (options.renderer) { |
| 63 | + try { |
| 64 | + const renderer = await import('vite-plugin-electron-renderer') |
| 65 | + plugins.push(renderer.default(options.renderer)) |
| 66 | + } catch (error: any) { |
| 67 | + if (error.code === 'ERR_MODULE_NOT_FOUND') { |
| 68 | + throw new Error( |
| 69 | + `\`renderer\` option dependency "vite-plugin-electron-renderer" not found. Did you install it? Try \`npm i -D vite-plugin-electron-renderer\`.`, |
| 70 | + ) |
| 71 | + } |
| 72 | + |
| 73 | + throw error |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return plugins |
| 78 | +} |
0 commit comments