Vite + Electron + ESM project template.
Quickly get started using Vite and ESM in Electron without heavy boilerplate.
Out of the box:
- ESM support in Electron (as of v28.0.0).
- HMR (Hot-Module Replacement).
- Vanilla TypeScript with ESLint.
- Vitest for unit testing.
- As of now the example project should suffice for scaffolding a new project.
- Migrating an existing project to use this as a base is possible for most cases.
Submit a issue if you have problems with the setup or migration process.
Fork repository (optional)
Clone repository
git clone <SSH/HTTPS URL>
Change directory
cd <...>/Electron-ESM-Vite
Install npm dependencies
npm install
Run dev server
npm run dev
Run unit tests
npm run test
Package app for distribution
# package for macOS platform (universal)
npm run package:mac
# package for Windows platform
npm run package:windows
# package for Linux platform
npm run package:linux
The packaged app can be found in dist
.
When you run npm run dev
, it will do the following steps:
- Compile TypeScript files (TSC) and other production files (Vite) into
out
. The main entry point for Electron needs to be compiled to.js
. - Launch Vite dev server. Vite will serve the root directory during development. Loaded files will be based on the non-compiled/bundled version (i.e.,
.ts
). - Spawn Electron process in root directory and load Vite dev server URL in the browser window.
- Run
cli.js
to activate HMR. - Renderer is contextIsolated and unsanboxed in order to execute ESM preload scripts. As the renderer is contextIsolated and unsandboxed, all preload scripts must have the
.mjs
extension. - When
index.html
, main, preload, and renderer files detect a change, it will rebuild the production files, kill the current Electron process, and re-spawn a new Electron process. Chokidar is a dependency for the HMR implementation, so don't remove it.
-
.hmr_pid.txt
is an output file for the current Electron PID, which is used in HMR. -
If you are using a framework, you might need to update the glob pattern array in
chokidarPaths
andchokidarPathsIgnore
withincli.js
. -
Vite's HMR is disabled in favour of Electron-ESM-Vite's custom one using Chokidar (
cli.js
/hmr()
). -
It is recommended to follow the same folder structure to avoid any path issues.