插件:vite-plugin-electron

发布于:2024-06-06 ⋅ 阅读:(154) ⋅ 点赞:(0)

源文档地址:vite-plugin-electron

安装

npm i -D vite-plugin-electron

将vite-plugin-electron添加到vite.config.ts的插件部分

import electron from 'vite-plugin-electron/simple'

export default {
  plugins: [
    electron({
      main: {
        // `build.lib.entry的快捷方式`
        entry: 'electron/main.ts',
      },
      preload: {
        //`build.rollupOptions.input的快捷方式`
        input: 'electron/preload.ts',
      },
      // 可选:在渲染器进程中使用Node.js API
      renderer: {},
    }),
  ],

创建electron/main.ts文件并键入以下代码

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');
  }
})

将主条目添加到package.json

{
+ "main": "dist-electron/main.mjs"
}

Flat API

在大多数情况下,建议使用vite-lugin-election/简单API。如果你非常了解这个插件的工作原理,或者你想使用vite-plugin-electronic API作为低级API的二次封装,那么平面API更适合你。它也很简单,但更灵活。:)

与简单的API相比,不同之处在于它没有识别哪个条目表示预加载和对预加载的适应。

import electron from 'vite-plugin-electron'

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

Flat API vs Simple API

简单API基于平面API
简单的API包含一些预加载脚本预设配置。
Flat API提供了一些更通用的API,可以用于二次封装,例如nuxt-electron。

electron(options:ElectroOptions|ElectroOptions])

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']`
     * @param options options for `child_process.spawn`
     * @param customElectronPkg custom electron package name (default: 'electron')
     */
    startup: (argv?: string[], options?: import('node:child_process').SpawnOptions, customElectronPkg?: string) => Promise<void>
    /** Reload Electron-Renderer */
    reload: () => void
  }) => void | Promise<void>
}

推荐结构

让我们以基于create vite创建的官方模板vanilla ts为例

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

内置格式

这只是默认行为,您可以通过vite.config.js中的自定义配置随时修改它们

{ "type": "module" }
┏————————————————————┳——————————┳———————————┓
│       built        │  format  │   suffix  │
┠————————————————————╂——————————╂———————————┨
│ main process       │   esm    │    .js    │
┠————————————————————╂——————————╂———————————┨
│ preload scripts    │   cjs    │   .mjs    │ diff
┠————————————————————╂——————————╂———————————┨
│ renderer process   │    -     │    .js    │
┗————————————————————┸——————————┸———————————┛

{ "type": "commonjs" } - default
┏————————————————————┳——————————┳———————————┓
│       built        │  format  │   suffix  │
┠————————————————————╂——————————╂———————————┨
│ main process       │   cjs    │    .js    │
┠————————————————————╂——————————╂———————————┨
│ preload scripts    │   cjs    │    .js    │ diff
┠————————————————————╂——————————╂———————————┨
│ renderer process   │    -     │    .js    │
┗————————————————————┸——————————┸———————————┛

JavaScript API

vite-plugin-electron的JavaScript API是完全类型化的,建议在VS Code中使用TypeScript或启用JS类型检查,以利用智能感知和验证。

electron-options
resolveViteConfig-函数,为构建Electron Main解析默认Vite的InlineConfig
带有ExternalBuiltins-功能
构建-功能
启动-功能

例子

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

如何工作

它只是执行电子。命令,然后启动或重新启动Electron应用程序。

注意:默认情况下,electron文件夹中的文件将内置到dist-electron中。目前,Electron不支持“类型”:“模块”

原生C/C++

我们有两种方法来使用C/C++原生模块

第一种方式

一般来说,Vite可能无法正确构建Node.js包,尤其是C/C++原生模块,但Vite可以将其作为外部包加载,因此,将Node.js包放在依赖项中。除非你知道如何用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',
            ],
          },
        },
      },
    }),
  ],
}

第二种方式

使用https://github.com/vite-plugin/vite-plugin-native

import native from 'vite-plugin-native'

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

Not Bundle

在开发阶段,我们可以从bundle中排除npm-pkg的cjs格式。就像Vite的Not Bundle。它很快!

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

export default defineConfig(({ command }) => ({
  plugins: [
    electron({
      entry: 'electron/main.ts',
      vite: {
        plugins: [
          command === 'serve' && notBundle(/* NotBundleOptions */),
        ],
      },
    }),
  ],
}))

api    (notBundle(/* NotBundleOptions */))

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

如何使用

让我们以electron-log 为例。

┏—————————————————————————————————————┓
│ import log from 'electron-log'      │
┗—————————————————————————————————————┛
                   ↓
Modules in `node_modules` are not bundled during development, it's fast!
                   ↓
┏—————————————————————————————————————┓
│ const log = require('electron-log') │
┗—————————————————————————————————————┛


网站公告

今日签到

点亮在社区的每一天
去签到