vite-plugin-electron-renderer
Support use Node.js API in Electron-Renderer
Install
npm i vite-plugin-electron-renderer -D
Usage
vite.config.ts
import renderer from 'vite-plugin-electron-renderer'
export default {
plugins: [
renderer(),
],
}
renderer.js
import { readFile } from 'fs'
import { ipcRenderer } from 'electron'
readFile()
ipcRenderer.on('event-name', () => {})
API
renderer(options: Options)
export interface Options {
resolve?: (modules: string[]) => typeof modules | undefined
}
dependencies
vs devDependencies
The easiest way
- Put Node.js packages in
dependencies
- Put Web packages in
devDependencies
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.
通常的,Vite 可能不能正确的构建 Node.js 的包,尤其是 C/C++ 原生模块,但是 Vite 可以将它们以外部包的形式加载。所以,请将 Node.js 包放到 dependencies
中。除非你知道如何用 Vite 正确的构建它们。
e.g.
Electron-Main
import { ipcMain } from 'electron'
↓
const { ipcMain } = require('electron')
Electron-Renderer
import { ipcRenderer } from 'electron'
↓
const electron = require('electron')
export const ipcRenderer = electron.ipcRenderer
↓
import { ipcRenderer } from 'electron'
See more about Vite loading Node.js package 👉
How to work
Using Electron API in Electron-Renderer
import { ipcRenderer } from 'electron'
↓
import { ipcRenderer } from 'vite-plugin-electron-renderer/electron-renderer.js'
Using Node.js API and package in Electron-Renderer 👉
Config presets
- Fist, the plugin will configuration something.
If you do not configure the following options, the plugin will modify their default values
base = './'
build.assetsDir = ''
-> TODO: Automatic splicing build.assetsDir
build.emptyOutDir = false
build.cssCodeSplit = false
build.rollupOptions.output.format = 'cjs'
resolve.conditions = ['node']
- Always insert the
electron
module into optimizeDeps.exclude
-
The plugin transform Electron and Node.js built-in modules to ESModule format in vite serve
phase.
-
Add Electron and Node.js built-in modules to Rollup output.external
option in the vite build
phase.