Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vite-plugin-electron

Package Overview
Dependencies
Maintainers
1
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vite-plugin-electron

Electron 🔗 Vite

  • 0.13.0-beta.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
12K
decreased by-25.09%
Maintainers
1
Weekly downloads
 
Created
Source

vite-plugin-electron

Electron 🔗 Vite

English | 简体中文


Features

Quick Setup

  1. Add the following dependency to your project
npm i -D vite-plugin-electron
  1. Add vite-plugin-electron to the plugins section of vite.config.ts
import electron from 'vite-plugin-electron'

export default {
  plugins: [
    electron({
      entry: 'electron/main.ts',
    }),
  ],
}
  1. Create the electron/main.ts file and type the following code
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');
  }
})
  1. Add the main entry to package.json
{
+ "main": "dist-electron/main.js"
}

That's it! You can now use Electron in your Vite app ✨

API (Define)

electron(config: ElectronOptions | ElectronOptions[])

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 Electroo App via `startup` function.  
   */
  onstart?: (args: {
    /**
     * Electron App startup function.  
     * It will mount the Electron App child-process to `process.electronApp`.  
     * @param argv default value `['.', '--no-sandbox']`
     */
    startup: (argv?: string[]) => Promise<void>
    /** Reload Electron-Renderer */
    reload: () => void
  }) => void | Promise<void>
}

Recommend Structure

Let's use the official template-vanilla-ts created based on create vite as an example

+ ├─┬ electron
+ │ └── main.ts
  ├─┬ src
  │ ├── main.ts
  │ ├── style.css
  │ └── vite-env.d.ts
  ├── .gitignore
  ├── favicon.svg
  ├── index.html
  ├── package.json
  ├── tsconfig.json
+ └── vite.config.ts

Examples

JavaScript API

vite-plugin-electron's JavaScript APIs are fully typed, and it's recommended to use TypeScript or enable JS type checking in VS Code to leverage the intellisense and validation.

  • ElectronOptions - type
  • resolveViteConfig - function, Resolve the default Vite's InlineConfig for build Electron-Main
  • withExternalBuiltins - function
  • build - function
  • startup - function

Example

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()
        }
      },
    }],
  },
})

Not Bundle

During dev, we exclude the cjs npm-pkg from bundle. It's fast! Like Vite's 👉 Not Bundle. Only works during the vite serve phase by default.

import electron from 'vite-plugin-electron'
import { notBundle } from 'vite-plugin-electron/plugin'

export default {
  plugins: [
    electron({
      entry: 'electron/main.ts',
      vite: {
        plugins: [
          notBundle(/* NotBundleOptions */),
        ],
      },
    }),
  ],
}

notBundle(/* NotBundleOptions */)

export interface NotBundleOptions {
  filter?: (id: string) => void | false
}

How to work

It just executes the electron . command in the Vite build completion hook and then starts or restarts the Electron App.

Be aware

  • 🚨 By default, the files in electron folder will be built into the dist-electron
  • 🚨 Currently, "type": "module" is not supported in Electron

C/C++ Native

We have two ways to use C/C++ native modules

First way

In general, Vite may not correctly build Node.js packages, especially C/C++ native modules, but Vite can load them as external packages

So, put your Node.js package in dependencies. Unless you know how to properly build them with Vite

export default {
  plugins: [
    electron({
      entry: 'electron/main.ts',
      vite: {
        build: {
          rollupOptions: {
            // Here are some C/C++ modules them can't be built properly
            external: [
              'serialport',
              'sqlite3',
            ],
          },
        },
      },
    }),
  ],
}

Second way

Use 👉 vite-plugin-native

import native from 'vite-plugin-native'

export default {
  plugins: [
    electron({
      entry: 'electron/main.ts',
      vite: {
        plugins: [
          native(/* options */),
        ],
      },
    }),
  ],
}

Keywords

FAQs

Package last updated on 21 Aug 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc