PromptHub
Back to Blog
Developer Tools Electron

Stop Wrestling with Electron Forge! electron-vite Is the Build Tool You Need

B

Bright Coding

Author

13 min read 28 views
Stop Wrestling with Electron Forge! electron-vite Is the Build Tool You Need

Stop Wrestling with Electron Forge! electron-vite Is the Build Tool You Need

Your Electron build takes 45 seconds. Every. Single. Time. You tweak one line of CSS, and you're staring at a progress bar, contemplating your career choices. Your preload script bundler is a Frankenstein of webpack configs you copied from Stack Overflow in 2019. And don't get me started on the nightmare of protecting your source code when shipping to production.

Sound familiar? You're not alone.

For years, Electron developers have accepted sluggish builds as an inevitable tax on cross-platform desktop development. We've tolerated complex configuration rituals, prayed our HMR wouldn't crash the entire main process, and accepted that "production-ready" meant shipping readable JavaScript↗ Bright Coding Blog to anyone with a right-click menu.

But what if I told you there's a tool that eliminates this pain entirely? A tool that brings Vite's legendary speed to Electron development without sacrificing a single feature you actually need?

Enter electron-vite — the next-generation Electron build tooling that's making experienced developers abandon their old setups in droves. Created by alex8088, this isn't another wrapper around tired bundlers. It's a ground-up reimagining of how Electron development should feel: fast, intuitive, and genuinely enjoyable.

Ready to reclaim hours of your life? Let's dive into why electron-vite is becoming the secret weapon of top Electron developers worldwide.


What Is electron-vite?

electron-vite is next-generation Electron build tooling powered by Vite — the same build tool that revolutionized web development↗ Bright Coding Blog with its instant server start and lightning-fast hot module replacement. But this isn't simply Vite slapped onto Electron. It's a purpose-built solution that understands Electron's unique architecture: the main process, preload scripts, and renderer processes, each with different constraints and requirements.

The project was created by alex8088 (alex.wei), a developer who clearly experienced the same frustrations we all have. The repository's Chinese tagline — "新一代 Electron 开发构建工具,支持源代码保护" — reveals its dual mission: modernize the developer experience and solve the production security problem that's plagued Electron apps forever.

Here's why electron-vite is trending right now:

  • Vite's ecosystem dominance: With Vite now the default for Vue, React↗ Bright Coding Blog, Svelte, and countless frameworks, developers want that same experience everywhere.
  • Electron's stubborn complexity: Despite improvements, Electron's build tooling remained stuck in the webpack era, creating a painful gap.
  • Source code protection demand: As commercial Electron applications proliferate, the need for legitimate source protection has exploded.
  • TypeScript-first mentality: Modern developers expect TypeScript support without configuration gymnastics.

The project sits at a perfect intersection: it leverages Vite's mature, battle-tested infrastructure while adding Electron-specific optimizations that generic tools simply cannot provide. It's not a plugin or a hack — it's comprehensive tooling that treats Electron as a first-class citizen.


Key Features That Change Everything

electron-vite isn't a minor improvement. It's a fundamental rethinking of Electron build tooling. Here's what makes it genuinely different:

⚡️ Native Vite Power, Zero Compromise

You use electron-vite the same way you use Vite. Same configuration patterns, same plugin ecosystem, same mental model. No learning cliff. If you've built a Vite project, you're already 90% proficient with electron-vite.

🛠 Sensible Defaults for Electron's Weirdness

Electron isn't a standard web app. You have Node.js in the main process, context-isolated preload scripts, and Chromium renderers. electron-vite pre-configures everything for these constraints — no more guessing which target to set or which externals to exclude.

💡 Asset Handling That Actually Works

Electron's main process handles assets differently than browsers. electron-vite optimizes asset paths and handling specifically for Electron's file system, eliminating the "works in dev, breaks in production" plague.

🚀 Fast HMR & Hot Reloading

See changes instantly without full process restarts. The main process, preload scripts, and renderers each get appropriate reloading strategies. You modify a preload script? Only that reloads. You change a React component? HMR handles it. This isn't theoretical — it's the difference between flow state and constant interruption.

🔥 Isolated Multi-Entry Builds

Complex Electron apps often need multiple renderers, multiple preload scripts, or even multiple main process entry points. electron-vite builds these in isolation with proper dependency handling, preventing the cross-contamination bugs that plague monolithic builds.

✨ Multi-Threading Made Simple

Electron apps increasingly use Node.js worker threads or Web Workers. electron-vite simplifies their development with dedicated build configurations, so you stop treating threading as an afterthought.

🔒 V8 Bytecode Compilation for Source Protection

This is the feature that makes commercial developers switch. electron-vite can compile your code to V8 bytecode, making source extraction practically impossible. Your intellectual property stays protected without external tools or complex post-build steps.

🔌 IDE Debugging Without Tears

Source maps that actually work. Breakpoints that stick. VSCode and WebStorm configurations that don't require tribal knowledge. electron-vite generates proper debug configurations for each process.

📦 Framework Agnostic Out of the Box

TypeScript, Vue, React, Svelte, SolidJS — all supported without additional configuration. Use your preferred stack without fighting the build tool.


Real-World Use Cases Where electron-vite Dominates

1. Commercial Desktop Applications

You're shipping a SaaS desktop client or licensed software. Source code exposure isn't acceptable. electron-vite's V8 bytecode compilation gives you production-grade protection without the complexity of electron-builder hooks or third-party packers. Your competitors can't simply extract your ASAR and read your business logic.

2. Rapid Prototyping & MVPs

Need to validate a desktop app concept in days? The create-electron scaffolding gets you running in minutes, not hours. Hot reloading keeps you in creative flow, and when you're ready to ship, the same configuration scales to production.

3. Complex Multi-Window Applications

Dashboard apps, creative tools, or trading platforms with dozens of specialized windows. electron-vite's isolated multi-entry builds prevent the dependency hell where one window's massive library bloats every other process. Each entry gets optimal bundling.

4. Applications with Heavy Computation

Video editors, data processors, or scientific tools using worker threads. electron-vite's simplified multi-threading development means your worker scripts get proper bundling, source maps, and HMR — no separate build pipeline required.

5. Teams Migrating from Legacy Electron Tooling

Still on electron-webpack or custom gulp scripts? The migration path to electron-vite is surprisingly smooth. The configuration structure mirrors Vite's familiar patterns, and the Electron-specific defaults eliminate the "why doesn't this work?" debugging sessions that consume sprint time.


Step-by-Step Installation & Setup Guide

Prerequisites

  • Node.js 16+ (18+ recommended)
  • npm, yarn, or pnpm
  • Basic familiarity with Vite (helpful but not required)

Method 1: Quick Start with create-electron (Recommended)

The fastest path to a working project:

# Scaffold a new project with your preferred framework
npm create @quick-start/electron@latest

You'll be prompted to choose:

  • Framework: vanilla, vue, react, svelte, or solid
  • Language: JavaScript or TypeScript

This generates a complete project structure with electron-vite pre-configured.

Method 2: Add to Existing Project

Already have an Electron project? Migrate incrementally:

# Install as dev dependency
npm i electron-vite -D

Add scripts to your package.json:

{
  "scripts": {
    "start": "electron-vite preview",
    "dev": "electron-vite dev",
    "prebuild": "electron-vite build"
  }
}

Configuration File Setup

electron-vite automatically resolves electron.vite.config.js (or .ts) from your project root. Create this file:

// electron.vite.config.js
export default {
  main: {
    // Vite config for main process (Node.js environment)
    build: {
      sourcemap: true,
      minify: process.env.NODE_ENV === 'production'
    }
  },
  preload: {
    // Vite config for preload scripts (context-isolated, limited Node.js)
    build: {
      sourcemap: true,
      rollupOptions: {
        // Preload scripts should be single-file bundles
        output: {
          inlineDynamicImports: true
        }
      }
    }
  },
  renderer: {
    // Vite config for renderer processes (Chromium environment)
    // This is standard Vite configuration you're already familiar with
    build: {
      sourcemap: true
    }
  }
}

Environment-Specific Configuration

For advanced setups, use conditional configuration:

// electron.vite.config.js
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'

export default defineConfig(({ command }) => {
  const isServe = command === 'serve'
  
  return {
    main: {
      plugins: [
        // Automatically externalize Node.js dependencies
        externalizeDepsPlugin()
      ],
      build: {
        // Development: fast builds with source maps
        // Production: optimized, bytecode-protected builds
        sourcemap: isServe ? 'inline' : false
      }
    },
    // ... preload and renderer configs
  }
})

Development Workflow

# Start development server with HMR
npm run dev

# Preview production build locally
npm run start

# Build for production (typically called before packaging)
npm run prebuild

REAL Code Examples from the Repository

Let's examine actual patterns from electron-vite's documentation and boilerplate, with detailed explanations of how each piece works.

Example 1: Basic Configuration Structure

// electron.vite.config.js — The foundation of every electron-vite project
export default {
  main: {
    // vite config options for the main process
    // This runs in Node.js, so you have full access to fs, path, etc.
    // electron-vite automatically sets appropriate defaults:
    // - target: 'node16' or higher based on your Electron version
    // - format: 'cjs' (CommonJS, required by Electron's require())
    // - platform: 'node' (enables Node.js built-ins)
  },
  preload: {
    // vite config options for preload scripts
    // Critical security context: runs in isolated world with limited privileges
    // electron-vite ensures proper sandbox-compatible output
    // - contextIsolation: true compatibility
    // - single file output (no code splitting that breaks context isolation)
  },
  renderer: {
    // vite config options for renderer processes
    // Standard browser environment — use any Vite plugin here
    // React, Vue, Svelte plugins work identically to web projects
  }
}

Why this matters: Traditional Electron build tools force you to manage three separate bundlers or one monolithic config that compromises somewhere. electron-vite's tripartite structure gives each process exactly what it needs without cross-process pollution. The main process gets Node.js externals handled automatically; preload gets security-constrained output; renderer gets full web tooling.

Example 2: NPM Scripts Integration

{
  "scripts": {
    "start": "electron-vite preview",
    "dev": "electron-vite dev",
    "prebuild": "electron-vite build"
  }
}

Command breakdown:

  • electron-vite dev: Starts the Vite dev server for renderers and watches main/preload files with appropriate reloading. The -- separator lets you pass Electron CLI flags: npm run dev -- --remote-debugging-port=9223
  • electron-vite preview: Builds production assets and launches Electron for verification. Essential for catching production-only bugs before release.
  • electron-vite build: Compiles all processes for production. Add --sourcemap for debugging builds, or configure bytecode compilation here.

Example 3: Project Scaffolding Command

npm create @quick-start/electron@latest

What happens under the hood:

This executes the create-electron tool from the @quick-start scope, which:

  1. Prompts for framework and language preferences
  2. Clones the appropriate template from the quick-start monorepo
  3. Installs dependencies with your package manager
  4. Initializes git repository
  5. Provides immediate npm run dev capability

The template presets cover the full modern frontend spectrum:

JavaScript TypeScript
vanilla vanilla-ts
vue vue-ts
react react-ts
svelte svelte-ts
solid solid-ts

Pro tip: The TypeScript templates include tsconfig.json configurations properly separated for main, preload, and renderer contexts — each with appropriate lib and types settings. No more tsconfig.json conflicts between Node.js and DOM environments.

Example 4: Source Code Protection Configuration

While not explicitly shown in the README, the repository's tagline and features indicate bytecode compilation capability. Based on electron-vite's architecture, protection is configured in the build step:

// electron.vite.config.js — Production build with source protection
import { bytecodePlugin } from 'electron-vite'

export default {
  main: {
    plugins: [
      // Convert JavaScript to V8 bytecode for source protection
      // This makes reverse engineering significantly harder
      bytecodePlugin()
    ],
    build: {
      // Ensure proper handling for bytecode generation
      minify: 'terser',
      terserOptions: {
        // Additional obfuscation if desired
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      }
    }
  },
  // preload and renderer configurations...
}

Security implications: V8 bytecode isn't cryptographic security — determined attackers with sufficient resources can eventually reverse it. However, it raises the barrier dramatically compared to shipping raw JavaScript. For most commercial applications, this combined with ASAR integrity checks provides adequate protection against casual extraction and competitor analysis.


Advanced Usage & Best Practices

Optimize Your Development Experience

Use externalizeDepsPlugin for main process: Automatically externalizes dependencies in package.json, preventing bundle bloat and native module issues:

import { externalizeDepsPlugin } from 'electron-vite'

export default {
  main: {
    plugins: [externalizeDepsPlugin()]
  }
}

Handle Native Modules Correctly

Native Node.js modules (SQLite, sharp, etc.) require special handling. In your main process config:

main: {
  build: {
    rollupOptions: {
      // Don't bundle native modules — let Node.js require() handle them
      external: ['better-sqlite3', 'sharp']
    }
  }
}

Environment Variable Strategy

Use Vite's loadEnv with Electron-specific prefixes:

import { loadEnv } from 'vite'

export default ({ mode }) => {
  // Load .env files with ELECTRON_ prefix
  process.env = { ...process.env, ...loadEnv(mode, process.cwd(), 'ELECTRON_') }
  
  return {
    // your config
  }
}

Production Build Checklist

  1. ✅ Test electron-vite preview before packaging
  2. ✅ Verify source maps are disabled for protected builds
  3. ✅ Confirm native modules are properly externalized
  4. ✅ Check ASAR packaging handles your asset structure
  5. ✅ Validate auto-updater works with your build output paths

Comparison with Alternatives

Feature electron-vite Electron Forge Custom Webpack electron-builder
Build Speed ⚡️ Instant 🐢 Slow 🐢 Slow ⚡️ Fast (packaging)
HMR Quality ✅ True HMR ❌ Full restart ❌ Full restart N/A (packager only)
Config Complexity Minimal Moderate High Moderate
Source Protection ✅ Built-in ❌ External tools ❌ Manual setup ❌ External tools
Multi-Entry Support ✅ Native ⚠️ Plugin Manual N/A
Vite Ecosystem ✅ Full access ❌ Separate ❌ Separate N/A
TypeScript ✅ Zero config ⚠️ Setup required ⚠️ Complex setup N/A
Debugging ✅ IDE-ready ⚠️ Manual config ⚠️ Manual config N/A

When to choose electron-vite:

  • You value development speed and HMR quality
  • You're starting fresh or can migrate incrementally
  • Source code protection is a requirement
  • Your team already knows Vite
  • You need multi-process or multi-threading builds

When alternatives might suffice:

  • Legacy project with massive custom webpack config (migration cost)
  • Simple single-window apps where build speed matters less
  • Deep integration with Electron Forge's plugin ecosystem

FAQ

Is electron-vite production-ready?

Yes. The project is actively maintained, has stable versioning, and is used in commercial applications. The MIT license and active issue resolution indicate mature governance.

Can I migrate from Electron Forge incrementally?

Absolutely. Start by replacing your development build with electron-vite while keeping Forge for packaging. Once comfortable, migrate packaging too, or keep the hybrid approach indefinitely.

Does source code protection affect performance?

V8 bytecode compilation has negligible runtime overhead — it's the same V8 engine executing pre-parsed code. Build time increases slightly due to the compilation step.

How do I debug the main process with VSCode?

electron-vite generates proper source maps for each process. Configure VSCode's launch.json to attach to the main process port, or use the built-in --remote-debugging-port flag for renderer debugging.

Can I use electron-vite with ESM-only packages?

Yes. electron-vite handles ESM/CJS interoperability better than many alternatives. The main process build targets appropriate formats automatically.

What Electron versions are supported?

Modern Electron versions (16+) work best. The tool tracks Electron's evolution, with configurations adapting to changes in context isolation, sandboxing, and other security features.

Is there a migration guide from electron-webpack?

The configuration structures differ significantly, but the create-electron templates provide working patterns. Community resources and GitHub discussions contain migration experiences from major projects.


Conclusion

electron-vite isn't incrementally better than existing Electron build tools — it's generationally different. By building on Vite's proven foundation and adding Electron-specific intelligence, it eliminates the friction that's slowed desktop development for years.

The combination of instant development feedback, production source protection, and genuine multi-process optimization creates a tool that works for weekend prototypes and enterprise applications alike. No more choosing between developer experience and production requirements.

I've watched too many talented developers abandon Electron projects because the tooling felt archaic compared to their web development workflow. electron-vite closes that gap completely. Your desktop applications deserve the same development joy as your web projects.

Ready to experience the difference?

👉 Star and explore electron-vite on GitHub

👉 Read the full documentation at electron-vite.org

👉 Scaffold your first project with npm create @quick-start/electron@latest

The future of Electron development is fast, protected, and genuinely enjoyable. Stop wrestling with your build tool — start building what matters.


Have you tried electron-vite? Share your experience in the comments, or tag me with your build time improvements. The community's migration stories are genuinely inspiring.

Comments (0)

Comments are moderated before appearing.

No comments yet. Be the first to share your thoughts!

All tools