### Build and Startup Example Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Example demonstrating how to use the `build` and `startup` functions from `vite-plugin-electron` to manage your Electron application's build and development server. ```APIDOC ## build and startup ### Description This example shows how to import and use the `build` and `startup` functions for managing Electron application builds and development workflows. ### Method JavaScript API ### Parameters `build` function accepts an options object: - `entry` (string): The entry point for the main process. - `vite` (object): Vite configuration object. - `mode` (string): The build mode (e.g., 'development', 'production'). - `build` (object): Vite build options. - `minify` (boolean): Whether to minify the build output. - `watch` (object | null): Watch options for development. - `plugins` (array): Array of Vite plugins. - `name` (string): The name of the plugin. - `closeBundle` (function): A hook that is called after the bundle is generated. `startup` function can be called to start the Electron app. ### Request Example ```js import { build, startup } from 'vite-plugin-electron' const isDev = process.env.NODE_ENV === 'development' const isProd = process.env.NODE_ENV === 'production' build({ entry: 'electron/main.ts', vite: { mode: process.env.NODE_ENV, build: { minify: isProd, watch: isDev ? {} : null, }, plugins: [ { name: 'plugin-start-electron', closeBundle() { if (isDev) { // Startup Electron App startup() } }, }, ], }, }) ``` ### Startup Env Vars `startup()` uses these environment variables to configure command-line flags for the Electron process: - `REMOTE_DEBUGGING_PORT`: Appends `--remote-debugging-port=`. - `ELECTRON_IGNORE_CERTIFICATE_ERRORS`: Appends `--ignore-certificate-errors`. - `ELECTRON_DISABLE_WEB_SECURITY`: Appends `--disable-web-security`. - `ELECTRON_INSPECT`: Appends `--inspect` or `--inspect=`. - `ELECTRON_INSPECT_BRK`: Appends `--inspect-brk` or `--inspect-brk=`. ### Startup Controls Automatic Electron app startup can be prevented using `startup.prevent = true`, `ELECTRON_STARTUP_PREVENT=1`, or `ELECTRON_STARTUP_PREVENT=true`. To manually start the app, set `startup.prevent = false; startup()`. The return value of `startup()` indicates whether the startup was triggered or prevented. ### Custom Electron Package Resolution The `startup(argv, options, customElectronPkg)` function supports custom Electron forks. The package is resolved from application roots before falling back to standard module resolution. An error is thrown if the package cannot be resolved. ``` -------------------------------- ### Build and Startup Electron App Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Example of using `build` and `startup` functions from 'vite-plugin-electron'. Includes configuration for development and production modes, and a plugin to trigger startup on bundle completion in development. ```javascript import { build, startup } from 'vite-plugin-electron' const isDev = process.env.NODE_ENV === 'development' const isProd = process.env.NODE_ENV === 'production' build({ entry: 'electron/main.ts', vite: { mode: process.env.NODE_ENV, build: { minify: isProd, watch: isDev ? {} : null, }, plugins: [ { name: 'plugin-start-electron', closeBundle() { if (isDev) { // Startup Electron App startup() } }, }, ], }, }) ``` -------------------------------- ### Install Demo Package Dependencies Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/playground/README.md If you need to work on a single demo package directly, run installs from inside each package folder using the --dir flag. ```sh pnpm --dir playground/flat install ``` ```sh pnpm --dir playground/multi-env install ``` ```sh pnpm --dir playground/simple install ``` ```sh pnpm --dir playground/worker install ``` -------------------------------- ### Project Structure Example Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Illustrates a recommended directory structure for an Electron-Vite project, including main process files and source directories. ```diff + ├─┬ electron + │ └── main.ts ├─┬ src │ ├── main.ts │ ├── style.css │ └── vite-env.d.ts ├── .gitignore ├── favicon.svg ├── index.html ├── package.json ├── tsconfig.json + └── vite.config.ts ``` -------------------------------- ### Install Dependencies from Repo Root Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/playground/README.md Run this command once from the repo root to install dependencies and allow pnpm to resolve workspace packages. ```sh pnpm install ``` -------------------------------- ### Create Electron Main Process File Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Example of an Electron main process file (`electron/main.ts`) that sets up the main window and handles loading the application. It checks for a development server URL or loads the production HTML file. ```js import { app, BrowserWindow } from 'electron' app.whenReady().then(() => { const win = new BrowserWindow({ title: 'Main window', }) // You can use `process.env.VITE_DEV_SERVER_URL` when the vite command is called `serve` if (process.env.VITE_DEV_SERVER_URL) { win.loadURL(process.env.VITE_DEV_SERVER_URL) } else { // Load your file win.loadFile('dist/index.html') } }) ``` -------------------------------- ### Install vite-plugin-electron Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Add vite-plugin-electron as a development dependency to your project. ```sh npm i -D vite-plugin-electron ``` -------------------------------- ### Example of __dirname in ESM Electron main process Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Demonstrates how `__dirname` works in an ESM Electron main process file after `esmShim` has been applied. The shims are prepended by the plugin. ```typescript // electron/main.ts — __dirname works even in ESM output import { join } from 'node:path' // esmShim prepends: import { fileURLToPath } from 'node:url' // import { dirname } from 'node:path' // const __filename = fileURLToPath(import.meta.url) // const __dirname = dirname(__filename) const configPath = join(__dirname, 'config.json') ``` -------------------------------- ### Electron Main Process: Load URL or File Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Example of an Electron main process script that loads the development server URL during development or a local file in production. Requires `preload.mjs` for the renderer. ```typescript import { join } from 'node:path' import { app, BrowserWindow } from 'electron' app.whenReady().then(() => { const win = new BrowserWindow({ webPreferences: { contextIsolation: true, preload: join(__dirname, 'preload.mjs'), }, }) if (process.env.VITE_DEV_SERVER_URL) { win.loadURL(process.env.VITE_DEV_SERVER_URL) } else { win.loadFile(join(__dirname, '../dist/index.html')) } }) ``` -------------------------------- ### Integrate C/C++ Native Modules with vite-plugin-native Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md An alternative method for using C/C++ native modules is to integrate with `vite-plugin-native`. This approach involves adding the plugin to the Vite configuration within the Electron plugin setup. ```javascript import native from 'vite-plugin-native' export default { plugins: [ electron({ entry: 'electron/main.ts', vite: { plugins: [native(/* options */)], }, }), ], } ``` -------------------------------- ### Include environment type declarations in tsconfig.json Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Include the `vite-plugin-electron/electron-env` type declaration in your `tsconfig.json` to get TypeScript types for `process.env.VITE_DEV_SERVER_URL` and `process.electronApp`. ```json { "compilerOptions": { "types": [] }, "include": ["src", "electron", "vite-plugin-electron/electron-env"] } ``` -------------------------------- ### Typed usage of environment variables in Electron Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Example of using typed environment variables like `process.env.VITE_DEV_SERVER_URL` and `process.electronApp` within an Electron source file, after including the environment type declarations. ```typescript /// if (process.env.VITE_DEV_SERVER_URL) { // string in dev, runtime undefined in prod win.loadURL(process.env.VITE_DEV_SERVER_URL) } // process.electronApp: ChildProcess | undefined console.log(process.electronApp?.pid) ``` -------------------------------- ### Run Flat Demo from Package Directory Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/playground/README.md Alternatively, run or build the flat demo by navigating to the playground/flat/ directory and executing these commands. ```sh pnpm dev ``` ```sh pnpm build ``` -------------------------------- ### startup() - Electron process launcher Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `startup()` async function spawns the Electron child process, making it available on `process.electronApp`. It's automatically called by the plugin during `vite serve` but can also be used directly. It supports custom arguments, spawn options, and environment variables. ```APIDOC ## `startup()` — Electron process launcher A standalone async function that spawns the Electron child process, mounting it on `process.electronApp`. Called automatically by the plugin during `vite serve`, but also usable directly via the JavaScript API. Supports custom argv, spawn options, custom Electron forks, and environment-variable-driven CLI flags. Returns `true` if Electron was started, `false` if startup was prevented. ### Manual JavaScript API Usage ```ts import { build, startup } from 'vite-plugin-electron' const isDev = process.env.NODE_ENV === 'development' // Manual JavaScript API usage (outside of vite.config.ts) build({ entry: 'electron/main.ts', vite: { mode: process.env.NODE_ENV, build: { minify: !isDev, watch: isDev ? {} : null, }, plugins: [ { name: 'start-electron', closeBundle() { if (isDev) { startup( ['.', '--no-sandbox'], // argv { cwd: process.cwd() }, // SpawnOptions 'electron', // customElectronPkg (default) ) } }, }, ], }, }) ``` ### Controlling Startup and Communication ```ts // Prevent automatic startup until a condition is met import { startup } from 'vite-plugin-electron' startup.prevent = true // Later, when ready: startup.prevent = false const started = await startup() console.log(started) // true // Send IPC message to the running Electron process startup.send('electron-vite&type=hot-reload') // Kill the running Electron process startup.exit() ``` ### Startup Environment Variables Set these environment variables before running `vite serve` to influence Electron startup: | Variable | Electron CLI flag | |---|---| | `REMOTE_DEBUGGING_PORT=9229` | `--remote-debugging-port=9229` | | `ELECTRON_INSPECT=1` | `--inspect` | | `ELECTRON_INSPECT_BRK=9229` | `--inspect-brk=9229` | | `ELECTRON_DISABLE_WEB_SECURITY=1` | `--disable-web-security` | | `ELECTRON_IGNORE_CERTIFICATE_ERRORS=1` | `--ignore-certificate-errors` | | `ELECTRON_STARTUP_PREVENT=1` | Prevent startup entirely | ``` -------------------------------- ### Custom Electron Startup with `onstart` Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Use the `onstart` option to replace the default `startup()` call. This allows for delayed Electron launches or integration with other services. It provides `startup` and `reload` callbacks for controlling the Electron process. ```typescript import electron from 'vite-plugin-electron' export default { plugins: [ electron({ entry: 'electron/main.ts', onstart({ startup, reload }) { // reload(): sends full-reload to renderer + hot-reload IPC to main // startup(): launches / restarts Electron console.log('Build finished — starting Electron') startup(['.', '--no-sandbox', '--inspect=5858']) }, }), ], } ``` ```typescript // Preload-only hot reload (reload renderer without restarting main process) import electron from 'vite-plugin-electron' export default { plugins: [ electron([ { entry: 'electron/main.ts' }, { entry: 'electron/preload.ts', onstart({ reload }) { // Only reloads the renderer; does not restart Electron reload() }, }, ]), ], } ``` -------------------------------- ### Run Simple Demo from Repo Root Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/playground/README.md Execute these commands from the repo root to run or build the simple demo. This demo exercises the simple API with preload rebuild hot reload behavior. ```sh pnpm play:simple ``` ```sh pnpm play:build:simple ``` -------------------------------- ### Run Flat Demo from Repo Root Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/playground/README.md Execute these commands from the repo root to run or build the flat demo. The flat demo is located in playground/flat/ and uses playground/flat/vite.config.ts to import src/index.ts. ```sh pnpm play ``` ```sh pnpm play:build ``` -------------------------------- ### Run Multi-Env Demo from Repo Root Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/playground/README.md Execute these commands from the repo root to run or build the multi-env demo. This demo configures named Electron environments and builds multiple main-process entries. ```sh pnpm play:multi-env ``` ```sh pnpm play:build:multi-env ``` -------------------------------- ### Run Worker Demo from Repo Root Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/playground/README.md Execute these commands from the repo root to run or build the worker demo. This demo verifies the flat API with multiple Electron entries. ```sh pnpm play:worker ``` ```sh pnpm play:build:worker ``` -------------------------------- ### Configure Electron with Simple API and Vite Plugins Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Use the simple API for a higher-level configuration, recommended for new projects. Includes options for main, preload, and renderer processes, with Vite plugins for development optimizations. ```typescript import { defineConfig } from 'vite' import electronSimple from 'vite-plugin-electron/simple' import { notBundle, esmShim } from 'vite-plugin-electron/plugin' export default defineConfig(({ command }) => ({ plugins: [ await electronSimple({ main: { entry: 'electron/main.ts', vite: { // Avoid bundling node_modules in dev for faster rebuilds plugins: [command === 'serve' && notBundle(), esmShim()], }, }, preload: { // Uses rolldownOptions.input; enables code-splitting-free CJS output input: 'electron/preload.ts', }, // Uncomment to allow Node.js APIs in the renderer process: // renderer: {}, }), ], })) ``` -------------------------------- ### Manual Electron Process Startup and Control Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Use the `startup()` function for manual Electron process management outside of `vite.config.ts`. It supports custom arguments, spawn options, and can be controlled via `startup.prevent`, `startup.send`, and `startup.exit`. ```typescript import { build, startup } from 'vite-plugin-electron' const isDev = process.env.NODE_ENV === 'development' // Manual JavaScript API usage (outside of vite.config.ts) build({ entry: 'electron/main.ts', vite: { mode: process.env.NODE_ENV, build: { minify: !isDev, watch: isDev ? {} : null, }, plugins: [ { name: 'start-electron', closeBundle() { if (isDev) { startup( ['.', '--no-sandbox'], // argv { cwd: process.cwd() }, // SpawnOptions 'electron', // customElectronPkg (default) ) } }, }, ], }, }) ``` ```typescript // Prevent automatic startup until a condition is met import { startup } from 'vite-plugin-electron' startup.prevent = true // Later, when ready: startup.prevent = false const started = await startup() console.log(started) // true // Send IPC message to the running Electron process startup.send('electron-vite&type=hot-reload') // Kill the running Electron process startup.exit() ``` -------------------------------- ### electronSimple() - Multi-env simple API Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `electronSimple()` named export from `vite-plugin-electron/multi-env` offers the same ergonomics as the default simple API but uses the Environment API for builds. It reuses presets for `main` and `preload`, treating additional keys as main-process-style targets. ```APIDOC ## `electronSimple()` — Multi-env simple API (`vite-plugin-electron/multi-env`) The named-export `electronSimple` from `vite-plugin-electron/multi-env` provides the same ergonomics as the default simple API but delegates builds to the Environment API. The `main` and `preload` keys reuse the same default presets as `vite-plugin-electron/simple`; additional keys are treated as main-process-style targets. ### Usage ```ts // vite.config.ts import { defineConfig } from 'vite' import { electronSimple } from 'vite-plugin-electron/multi-env' export default defineConfig({ plugins: [ electronSimple({ main: { input: ['electron/main.ts', 'electron/worker.ts'], options: { define: { __TARGET__: JSON.stringify('main') }, }, }, preload: { input: 'electron/preload.ts', options: { define: { __TARGET__: JSON.stringify('preload') }, }, }, // Custom target — built like main process sandbox: { input: 'electron/sandbox.ts', options: { define: { __TARGET__: JSON.stringify('sandbox') }, }, }, }), ], }) ``` ``` -------------------------------- ### Configure Electron Main Process with Flat API Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Use the flat API for single entry point configuration, suitable for main process only. Allows overriding Vite sub-build configurations. ```typescript import { defineConfig } from 'vite' import electron from 'vite-plugin-electron' export default defineConfig({ plugins: [ // Single entry — main process only electron({ entry: 'electron/main.ts', // Optional: override any Vite sub-build config vite: { build: { rolldownOptions: { // Externalize native addons that cannot be bundled external: ['serialport', 'sqlite3'], }, }, }, }), ], }) ``` -------------------------------- ### Configure vite-plugin-electron (Simple API) Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Integrate vite-plugin-electron into your vite.config.ts using the simple API. This configures the main process entry point and preload script input. ```js import electron from 'vite-plugin-electron/simple' export default { plugins: [ electron({ main: { // Shortcut of `build.lib.entry` entry: 'electron/main.ts', }, preload: { // Shortcut of `build.rolldownOptions.input` (`build.rollupOptions.input` on Vite < 8) input: 'electron/preload.ts', }, // Optional: Use Node.js API in the Renderer process renderer: {}, }), ], } ``` -------------------------------- ### Configure Multi-Env Builds with `electronSimple()` Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `electronSimple` named export provides the same ergonomics as the default simple API but delegates builds to the Environment API. It allows for custom targets beyond 'main' and 'preload'. ```typescript // vite.config.ts import { defineConfig } from 'vite' import { electronSimple } from 'vite-plugin-electron/multi-env' export default defineConfig({ plugins: [ electronSimple({ main: { input: ['electron/main.ts', 'electron/worker.ts'], options: { define: { __TARGET__: JSON.stringify('main') }, }, }, preload: { input: 'electron/preload.ts', options: { define: { __TARGET__: JSON.stringify('preload') }, }, }, // Custom target — built like main process sandbox: { input: 'electron/sandbox.ts', options: { define: { __TARGET__: JSON.stringify('sandbox') }, }, }, }), ], }) ``` -------------------------------- ### Build Format Table (Module Type) Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Defines the built format and suffix for main process and preload scripts when the module type is set to 'module'. ```log { "type": "module" } ┏————————————————————┳——————————┳———————————┓ │ built │ format │ suffix │ ┠————————————————————╂——————————╂———————————┨ │ main process │ esm │ .js │ ┠————————————————————╂——————————╂———————————┨ │ preload scripts │ cjs │ .mjs │ diff ┠————————————————————╂——————————╂———————————┨ │ renderer process │ - │ .js │ ┗————————————————————┸——————————┸———————————┛ ``` -------------------------------- ### Configure Multi-Env Simple API Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Uses the simple API from `vite-plugin-electron/multi-env` to configure multiple Electron build targets, including main, preload, and custom targets with specific options. ```javascript import { electronSimple } from 'vite-plugin-electron/multi-env' export default { plugins: [ electronSimple({ main: { input: 'electron/main.ts', options: { define: { __ELECTRON_TARGET__: JSON.stringify('main'), }, }, }, preload: { input: 'electron/preload.ts', options: { define: { __ELECTRON_TARGET__: JSON.stringify('preload'), }, }, }, // You can also add custom targets, and they will be built in the same way as the main process, but with different environment variables. custom: { input: 'electron/custom.ts', options: { define: { __ELECTRON_TARGET__: JSON.stringify('custom'), }, }, }, }), ], } ``` -------------------------------- ### Configure Multi-Env Flat API Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Uses the flat API from `vite-plugin-electron/multi-env` to configure multiple Electron build targets. Specify entry points for each target. ```javascript import electron from 'vite-plugin-electron/multi-env' export default { plugins: [ electron([ { input: 'electron/main.ts', }, { input: 'electron/preload.ts', }, ]), ], } ``` -------------------------------- ### Update package.json for Electron Main Entry Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Add the 'main' field to your package.json to specify the entry point for the Electron main process after building. ```json { + "main": "dist-electron/main.mjs" } ``` -------------------------------- ### Configure Multiple Electron Entries with Flat API Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Configure multiple Electron entry points (e.g., main and worker) using an array with the flat API. ```typescript import electron from 'vite-plugin-electron' export default { plugins: [ electron([ { entry: 'electron/main.ts' }, { entry: 'electron/worker.ts' }, ]), ], } ``` -------------------------------- ### electron(options: ElectronOptions | ElectronOptions[]) Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md The main function to configure the electron-vite plugin. It accepts a single or an array of ElectronOptions to define build configurations. ```APIDOC ## electron(options: ElectronOptions | ElectronOptions[]) ### Description Configures the vite-plugin-electron with specified options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (ElectronOptions | ElectronOptions[]) - Required - Configuration for the Electron build. - **entry** (import('vite').LibraryOptions['entry']) - Optional - Shortcut of `build.lib.entry`. - **vite** (import('vite').InlineConfig) - Optional - Vite configuration. - **onstart** ((args: { startup: (argv?: string[], options?: import('node:child_process').SpawnOptions, customElectronPkg?: string) => Promise, reload: () => void }) => void | Promise) - Optional - Triggered when Vite is built. If provided, Electron App will not start automatically, but can be started via the `startup` function. - **args.startup** - Function to start the Electron App child-process. - **args.reload** - Function to reload Electron-Renderer. ### Request Example ```js import electron from 'vite-plugin-electron' export default { plugins: [ electron({ // Electron-vite plugin options }) ] } ``` ### Response None explicitly defined for this function call itself, as it's a plugin configuration. ``` -------------------------------- ### electron() — Flat API Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The low-level plugin factory. Accepts one or more ElectronOptions objects for full control over Electron entry points. ```APIDOC ## electron() — Flat API ### Description The low-level plugin factory. Accepts one `ElectronOptions` object or an array of them — one per Electron entry (main, preload, worker, etc.). Each entry gets its own Vite sub-build; the plugin waits for all entries to finish before starting the Electron process. This is the right choice when you need full control or are building a meta-framework wrapper on top of the plugin. ### Usage Examples #### Single entry — main process only ```ts // vite.config.ts import { defineConfig } from 'vite' import electron from 'vite-plugin-electron' export default defineConfig({ plugins: [ // Single entry — main process only electron({ entry: 'electron/main.ts', // Optional: override any Vite sub-build config vite: { build: { rolldownOptions: { // Externalize native addons that cannot be bundled external: ['serialport', 'sqlite3'], }, }, }, }), ], }) ``` #### Multiple entries (main + worker) ```ts // vite.config.ts — multiple entries (main + worker) import electron from 'vite-plugin-electron' export default { plugins: [ electron([ { entry: 'electron/main.ts' }, { entry: 'electron/worker.ts' }, ]), ], } ``` ``` -------------------------------- ### notBundle Plugin Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Use `notBundle()` in development to externalize dependencies in Electron entries. This keeps startup fast by skipping dependency bundling while running `vite serve`. For production builds, let bundling run as usual. ```APIDOC ## notBundle Plugin ### Description Use `notBundle()` in development to externalize dependencies in Electron entries. This keeps startup fast by skipping dependency bundling while running `vite serve`. For production builds, let bundling run as usual. ### API `notBundle(options?: NotBundleOptions)` ```ts export interface NotBundleOptions { /** * Override `build.rolldownOptions.external` (`build.rollupOptions.external` on Vite < 8). * * If omitted, dependencies from package.json * (dependencies/devDependencies/peerDependencies/optionalDependencies) * are externalized automatically. */ filter?: import('vite').RolldownOptions['external'] } ``` ``` -------------------------------- ### electron() - Multi-env flat API Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `electron()` function from `vite-plugin-electron/multi-env` allows building multiple Electron targets as named environments within a single Vite builder instance. Each entry is registered as `electron_` in Vite's environment map. ```APIDOC ## `electron()` — Multi-env flat API (`vite-plugin-electron/multi-env`) Uses Vite's Environment API to build multiple Electron targets as named environments within a single Vite builder instance, instead of spawning separate `build()` calls. Each entry is registered as `electron_` in Vite's environment map. This is available only in `vite-plugin-electron@>=1.0.0`. ### Usage ```ts // vite.config.ts import { defineConfig } from 'vite' import electron from 'vite-plugin-electron/multi-env' export default defineConfig({ plugins: [ electron([ { name: 'main', input: 'electron/main.ts', }, { name: 'preload', input: 'electron/preload.ts', }, { name: 'worker', input: 'electron/worker.ts', }, ]), ], }) // Vite environments created: electron_main, electron_preload, electron_worker ``` ``` -------------------------------- ### vite-plugin-electron/multi-env Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Utilizes Vite's Environment API for building Electron targets, offering a more concise and maintainable configuration for multi-target builds. ```APIDOC ## /multi-env ### Description Uses Vite's Environment API to build Electron targets. This approach is more concise and easier to maintain for multi-target builds. ### Usage #### Flat API ```js import electron from 'vite-plugin-electron/multi-env' export default { plugins: [ electron([ { input: 'electron/main.ts', }, { input: 'electron/preload.ts', }, ]), ], } ``` #### Simple API ```js import { electronSimple } from 'vite-plugin-electron/multi-env' export default { plugins: [ electronSimple({ main: { input: 'electron/main.ts', options: { define: { __ELECTRON_TARGET__: JSON.stringify('main'), }, }, }, preload: { input: 'electron/preload.ts', options: { define: { __ELECTRON_TARGET__: JSON.stringify('preload'), }, }, }, custom: { input: 'electron/custom.ts', options: { define: { __ELECTRON_TARGET__: JSON.stringify('custom'), }, }, }, }), ], } ``` ### Configuration for `electronSimple()` ```ts export interface MultiEnvElectronOptions { /** * Optional name for the Electron environment `electron_${name}`. * By default, the plugin will generate environment names like `electron_0`, * `electron_1`, etc. based on the order of the options provided. */ name?: string /** * Shortcut of `options.build.rolldownOptions.input` (`options.build.rollupOptions.input` on Vite < 8) */ input?: import('vite').BuildEnvironmentOptions['rolldownOptions']['input'] /** * Shortcut of `options.build.rolldownOptions.plugins` (`options.build.rollupOptions.plugins` on Vite < 8) */ plugins?: import('vite').BuildEnvironmentOptions['rolldownOptions']['plugins'] /** * Per-environment Vite options. */ options?: import('vite').EnvironmentOptions onstart?: ElectronOptions['onstart'] } ``` ``` -------------------------------- ### electronSimple() — Simple API Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt A higher-level async factory built on top of the flat API. It accepts a single object with main, preload, and optional renderer keys, applying sensible defaults for each process type automatically. ```APIDOC ## electronSimple() — Simple API (`vite-plugin-electron/simple`) ### Description A higher-level async factory built on top of the flat API. It accepts a single object with `main`, `preload`, and optional `renderer` keys, applying sensible defaults for each process type automatically: CJS output without code-splitting for preload scripts, hot-reload-on-rebuild for preload, and optional integration with `vite-plugin-electron-renderer`. This is the recommended starting point for new projects. ### Usage Examples #### Basic setup ```ts // vite.config.ts import { defineConfig } from 'vite' import electronSimple from 'vite-plugin-electron/simple' import { notBundle, esmShim } from 'vite-plugin-electron/plugin' export default defineConfig(({ command }) => ({ plugins: [ await electronSimple({ main: { entry: 'electron/main.ts', vite: { // Avoid bundling node_modules in dev for faster rebuilds plugins: [command === 'serve' && notBundle(), esmShim()], }, }, preload: { // Uses rolldownOptions.input; enables code-splitting-free CJS output input: 'electron/preload.ts', }, // Uncomment to allow Node.js APIs in the renderer process: // renderer: {}, }), ], })) ``` #### Example `electron/main.ts` ```ts // electron/main.ts — use VITE_DEV_SERVER_URL in dev, loadFile in prod import { join } from 'node:path' import { app, BrowserWindow } from 'electron' app.whenReady().then(() => { const win = new BrowserWindow({ webPreferences: { contextIsolation: true, preload: join(__dirname, 'preload.mjs'), }, }) if (process.env.VITE_DEV_SERVER_URL) { win.loadURL(process.env.VITE_DEV_SERVER_URL) } else { win.loadFile(join(__dirname, '../dist/index.html')) } }) ``` ``` -------------------------------- ### Configure vite-plugin-electron (Flat API) Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Integrate vite-plugin-electron into your vite.config.ts using the flat API. This provides a more flexible approach compared to the simple API, allowing for secondary encapsulation. ```js import electron from 'vite-plugin-electron' export default { plugins: [ electron({ entry: 'electron/main.ts', }), ], } ``` -------------------------------- ### Configure Multi-Env Builds with `electron()` Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Use the `electron()` function to build multiple Electron targets as named environments within a single Vite builder instance. This is available in `vite-plugin-electron@>=1.0.0`. ```typescript // vite.config.ts import { defineConfig } from 'vite' import electron from 'vite-plugin-electron/multi-env' export default defineConfig({ plugins: [ electron([ { name: 'main', input: 'electron/main.ts', }, { name: 'preload', input: 'electron/preload.ts', }, { name: 'worker', input: 'electron/worker.ts', }, ]), ], }) // Vite environments created: electron_main, electron_preload, electron_worker ``` -------------------------------- ### Define Electron Options Interface Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Defines the interface for Electron options, including entry points, Vite configurations, and lifecycle hooks like `onstart`. ```typescript export interface ElectronOptions { /** * Shortcut of `build.lib.entry` */ entry?: import('vite').LibraryOptions['entry'] vite?: import('vite').InlineConfig /** * Triggered when Vite is built every time -- `vite serve` command only. * * If this `onstart` is passed, Electron App will not start automatically. * However, you can start Electron App via `startup` function. */ onstart?: (args: { /** * Electron App startup function. * It will mount the Electron App child-process to `process.electronApp`. * * You can also set environment variables to control the Electron CLI flags. * Supported env vars: * - `REMOTE_DEBUGGING_PORT` * - `ELECTRON_IGNORE_CERTIFICATE_ERRORS` * - `ELECTRON_DISABLE_WEB_SECURITY` * - `ELECTRON_INSPECT` * - `ELECTRON_INSPECT_BRK` * * `1` or `true` turns a flag on, `0` or `false` turns it off, and any other non-empty * value is appended as `=`. * * @param argv default value `['.', '--no-sandbox']` * @param options options for `child_process.spawn` * @param customElectronPkg custom electron package name (default: 'electron') * @returns `true` if the Electron app is started, or `false` if the startup is prevented by `startup.prevent` or `ELECTRON_STARTUP_PREVENT` env var. */ startup: ( argv?: string[], options?: import('node:child_process').SpawnOptions, customElectronPkg?: string, ) => Promise /** Reload Electron-Renderer */ reload: () => void }) => void | Promise } ``` -------------------------------- ### Vite 7/8 Build Config Adapter with `compatRollupOptions()` Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Use `compatRollupOptions()` to normalize build configurations between Vite 7 and Vite 8. It automatically adjusts between `rolldownOptions` (Vite 8+) and `rollupOptions` (Vite < 8) based on the detected or specified Vite version. ```typescript import { compatRollupOptions } from 'vite-plugin-electron' const buildConfig = compatRollupOptions( { // Write using the Vite 8 key; the function converts it for Vite < 8 rolldownOptions: { input: 'electron/main.ts', platform: 'node', output: { format: 'cjs' }, }, }, // Optionally pass a version string; defaults to the installed Vite version // '7.0.0', ) // On Vite 8+: { rolldownOptions: { ... } } // On Vite 7: { rollupOptions: { ... } } ``` -------------------------------- ### Programmatic Electron Build with `build()` Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `build()` function programmatically wraps `vite build` with Electron-specific defaults. Use this in custom scripts to build Electron targets outside of the Vite plugin context. It applies external builtins and sets the output directory to `dist-electron`. ```typescript import { build } from 'vite-plugin-electron' await build({ entry: 'electron/main.ts', vite: { build: { minify: true, rolldownOptions: { external: ['better-sqlite3'], }, }, }, }) // Output: dist-electron/main.js (CJS) or dist-electron/main.mjs (ESM) ``` -------------------------------- ### compatRollupOptions() — Vite 7/8 build config adapter Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `compatRollupOptions` function adapts build configurations between Vite 7 and Vite 8. It ensures that `rolldownOptions` are used for Vite 8+ and `rollupOptions` for versions prior to Vite 7, simplifying cross-version compatibility. ```APIDOC ## compatRollupOptions() ### Description Adapts Vite build configuration between versions 7 and 8, handling `rolldownOptions` and `rollupOptions`. ### Method `compatRollupOptions(buildConfig: BuildOptions, viteVersion?: string): BuildOptions` ### Parameters #### Request Body - **buildConfig** (BuildOptions) - Required - The build configuration object, potentially using `rolldownOptions`. - **rolldownOptions** (RolldownOptions) - Used for Vite 8+. - **rollupOptions** (RollupOptions) - Used for Vite < 8. - **viteVersion** (string) - Optional - Explicit Vite version string to simulate. ### Request Example ```ts import { compatRollupOptions } from 'vite-plugin-electron' const buildConfig = compatRollupOptions( { rolldownOptions: { input: 'electron/main.ts', platform: 'node', output: { format: 'cjs' }, }, }, // '7.0.0' ) ``` ### Response - **BuildOptions** - The compatible build configuration object. ``` -------------------------------- ### build() — Programmatic Electron build Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `build` export allows you to programmatically build Electron targets outside of the Vite plugin context. It wraps `vite build` with Electron-specific defaults, such as externalizing builtins and setting the output directory to `dist-electron`. ```APIDOC ## build() ### Description Programmatically builds Electron targets with Vite defaults applied. ### Method `build(options?: ElectronBuildOptions)` ### Parameters #### Request Body - **options** (ElectronBuildOptions) - Optional - Configuration options for the build process. - **entry** (string) - Required - The entry point for the Electron main process. - **vite** (InlineConfig) - Optional - Vite configuration to merge with defaults. ### Request Example ```ts import { build } from 'vite-plugin-electron' await build({ entry: 'electron/main.ts', vite: { build: { minify: true, rolldownOptions: { external: ['better-sqlite3'], }, }, }, }) ``` ### Response - **Promise** - Resolves when the build is complete. ``` -------------------------------- ### Build Format Table (CommonJS Type) Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Defines the built format and suffix for main process and preload scripts when the module type is 'commonjs' (default). ```log { "type": "commonjs" } - default ┏————————————————————┳——————————┳———————————┓ │ built │ format │ suffix │ ┠————————————————————╂——————————╂———————————┨ │ main process │ cjs │ .js │ ┠————————————————————╂——————————╂———————————┨ │ preload scripts │ cjs │ .js │ diff ┠————————————————————╂——————————╂———————————┨ │ renderer process │ - │ .js │ ┗————————————————————┸——————————┸———————————┛ ``` -------------------------------- ### Define MultiEnvElectronOptions Interface Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Defines the interface for multi-environment Electron options, including optional names, input/plugin configurations, and per-environment Vite options. ```typescript export interface MultiEnvElectronOptions { /** * Optional name for the Electron environment `electron_${name}`. * * By default, the plugin will generate environment names like `electron_0`, * `electron_1`, etc. based on the order of the options provided. */ name?: string /** * Shortcut of `options.build.rolldownOptions.input` (`options.build.rollupOptions.input` on Vite < 8) */ input?: import('vite').BuildEnvironmentOptions['rolldownOptions']['input'] /** * Shortcut of `options.build.rolldownOptions.plugins` (`options.build.rollupOptions.plugins` on Vite < 8) */ plugins?: import('vite').BuildEnvironmentOptions['rolldownOptions']['plugins'] /** * Per-environment Vite options. */ options?: import('vite').EnvironmentOptions onstart?: ElectronOptions['onstart'] } ``` -------------------------------- ### Implement Hot Reload for Preload Scripts Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Listens for the `electron-vite&type=hot-reload` message in the main process and reloads all browser windows to apply changes from rebuilt preload scripts. ```javascript // electron/main.ts process.on('message', (msg) => { if (msg === 'electron-vite&type=hot-reload') { for (const win of BrowserWindow.getAllWindows()) { // Hot reload preload scripts win.webContents.reload() } } }) ``` -------------------------------- ### Use notBundle for Development Externalization Source: https://github.com/electron-vite/vite-plugin-electron/blob/main/README.md Use `notBundle()` in development to externalize dependencies, keeping startup fast by skipping dependency bundling during `vite serve`. For production, bundling runs as usual. This configuration is applied conditionally based on the Vite command. ```javascript import { defineConfig } from 'vite' import electron from 'vite-plugin-electron' import { notBundle } from 'vite-plugin-electron/plugin' export default defineConfig(({ command }) => ({ plugins: [ electron({ entry: 'electron/main.ts', vite: { plugins: [command === 'serve' && notBundle()], }, }), ], })) ``` -------------------------------- ### Handle hot-reload IPC message in main process Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt Listen for the `electron-vite&type=hot-reload` IPC message in the main process to manually reload webContents when a preload script is rebuilt. ```typescript import { BrowserWindow } from 'electron' process.on('message', (msg) => { if (msg === 'electron-vite&type=hot-reload') { for (const win of BrowserWindow.getAllWindows()) { win.webContents.reload() } } }) ``` -------------------------------- ### withExternalBuiltins() — Externalize Node/Electron builtins Source: https://context7.com/electron-vite/vite-plugin-electron/llms.txt The `withExternalBuiltins` utility function helps in externalizing Node.js and Electron built-in modules. It automatically adds relevant modules to the `build.rolldownOptions.external` (or `rollupOptions.external` for older Vite versions) and merges them with any existing external configurations. ```APIDOC ## withExternalBuiltins() ### Description Adds Node.js and Electron built-in modules to the external configuration for Vite builds. ### Method `withExternalBuiltins(options: InlineConfig): InlineConfig` ### Parameters #### Request Body - **options** (InlineConfig) - Required - The Vite build configuration object. - **build.rolldownOptions.external** (Array | string | RegExp | Function) - Optional - Custom external modules to merge. ### Request Example ```ts import { withExternalBuiltins } from 'vite-plugin-electron' import { build as viteBuild } from 'vite' const config = withExternalBuiltins({ build: { rolldownOptions: { input: 'electron/main.ts', external: ['serialport'], }, }, }) await viteBuild(config) ``` ### Response - **InlineConfig** - The modified Vite configuration object with built-ins externalized. ```