Skip to content

Latest commit

 

History

History
108 lines (90 loc) · 4.71 KB

README.zh-CN.md

File metadata and controls

108 lines (90 loc) · 4.71 KB

vite-plugin-electron-renderer

English | 简体中文

原理

Electron-Renderer(vite serve)

加载 Electron、Node.js CJS 包/内置模块/electron (示意图)

 ┏————————————————————————————————————————┓                 ┏—————————————————┓
 │ import { ipcRenderer } from 'electron' │                 │ Vite dev server │
 ┗————————————————————————————————————————┛                 ┗—————————————————┛
                 │                                                   │
                 │ 1. Pre-Bundling electron module into              │
                 │    node_modules/.vite-electron-renderer/electron  │
                 │                                                   │
                 │ 2. HTTP(Request): electron module                 │
                 │ ————————————————————————————————————————————————> │
                 │                                                   │
                 │ 3. Alias redirects to                             │
                 │    node_modules/.vite-electron-renderer/electron  │
                 │    ↓                                              │
                 │    const { ipcRenderer } = require('electron')    │
                 │    export { ipcRenderer }                         │
                 │                                                   │
                 │ 4. HTTP(Response): electron module                │
                 │ <———————————————————————————————————————————————— │
                 │                                                   │
 ┏————————————————————————————————————————┓                 ┏—————————————————┓
 │ import { ipcRenderer } from 'electron' │                 │ Vite dev server │
 ┗————————————————————————————————————————┛                 ┗—————————————————┛
Electron-Renderer(vite build)
  1. 将 "fs module" 插入到 rollupOptions.external.
  2. 修改 rollupOptions.output.formatcjs (如果你没显示的设置它).
import { ipcRenderer } from 'electron'

const { ipcRenderer } = require('electron')

Dependency Pre-Bundling

When you run vite for the first time, you may notice this message:

$ vite
Pre-bundling: serialport
Pre-bundling: electron-store
Pre-bundling: execa
Pre-bundling: node-fetch
Pre-bundling: got

为啥

通常的,Vite 可能不能正确的构建 Node.js 包,尤其是 Node.js C/C++ 原生模块,但是 Vite 可以将它们以外部包(external)的形式加载它们。
除非你知道如何用 Vite 正确的构建它们 -- 鲁迅 使用案例

顺带说一句. 如果一个 npm 包是个一纯 ESM 格式包,并且它自身的依赖也是 ESM 格式包,那么直接包名放到 optimizeDeps.exclude 中即可正常使用。
这里解释了它

dependenciesdevDependencies

分类 🌰 dependencies devDependencies
Node.js C/C++ 原生模块 serialport, sqlite3
Node.js CJS 包 electron-store
Node.js ESM 包 execa, got, node-fetch ✅ (推荐)
Web 包 Vue, React ✅ (推荐)

为啥推荐将可以正确构建的包放到 devDependencies 中?

这样做会减小 electron-builder 打包后的应用体积。