首页 > 其他分享 >插件:vite-plugin-electron

插件:vite-plugin-electron

时间:2024-06-06 19:01:08浏览次数:7  
标签:插件 plugin ts electron API main vite

源文档地址: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') │
┗—————————————————————————————————————┛

标签:插件,plugin,ts,electron,API,main,vite
From: https://blog.csdn.net/qq_55139096/article/details/139430285

相关文章

  • Revit二次开发-使用Advanced Installer打包插件安装包
    插件开发属于客户端开发,当我们交付产品给客户的时候,肯定用安装包的形式交付是最佳方案。所以我摸索了一下怎么用AdvancedInstaller来打包插件安装包。AdvancedInstaller简介AdvancedInstaller是一款功能强大且用户友好的Windows安装包制作工具,专门用于创建安装包(MSI、EX......
  • Stable diffusion prompts 使用语法、参数讲解、插件安装教程
    Stablediffusionprompts使用语法、参数讲解、插件安装教程本文基于StablediffusionWebUI进行讲解(安装在AutoDL上,安装在本地电脑上的也同样适用本教程)。初始界面:文件目录结构:上图红框中的4个文件夹是我们常用到的,embeddings放置训练的embedding模型,它可......
  • Spring运维之boot项目打包jar和插件运行并且设置启动时临时属性和自定义配置文件
    打包与运行window版本上制作我们要把idea中的程序抽取出来作为一个独立的jar包把jar包放到服务器上服务器是长期运行的我们就能随时访问了在Maven的生命周期中选择package打包功能在资源管理器中查找java-jar文件名.jarjava-jar文件名.jar但是我们在测试里面......
  • 如何用Golang写msf插件模块
    最近有空在看msf,发现msf里面有模块的源码是golang的,去翻了翻wiki,wiki上面的编写日期是2018.12.13,搜了下国内,好像没有这方面的文章,那就自己跟着做做记个笔记首先第一步自然是安装go,官方wiki上测试是在1.11.2通过,建议使用version>=1.11.2的go,怎么安装go我不再赘述注意事项......
  • tapPromise 函数 (绑定hooks方法)tapable 库,创建自定义插件的库
    tapPromise函数(绑定hooks方法)tapable库,创建自定义插件的库刚看到了一个插件的use函数//引入组件use(plugin:IPluginClass,options?:IPluginOption){if(this._checkPlugin(plugin)&&this.canvas){this._saveCustomAttr(plugin);constpluginRu......
  • vue3+vueCli实现自动引入 unplugin-auto-import插件版本问题
    vue3项目引入unplugin-auto-import后报错通过引入的方式constAutoImport=require('unplugin-auto-import/webpack');报错如下: 通过直接官网vue-cli方式直接引入 报错如下经测试,是unplugin-auto-import插件版本问题查看unplugin-auto-import插件版本:npmlistu......
  • SemanticKernel:添加插件
    SemanticKernel介绍SemanticKernel是一个SDK,它将OpenAI、AzureOpenAI和HuggingFace等大型语言模型(LLMs)与C#、Python和Java等传统编程语言集成在一起。SemanticKernel通过允许您定义插件来实现这一点,这些插件可以通过几行代码链接在一起。为什么需要添加插件?大语言模型虽然......
  • 【软件插件】SketchUP插件-最新版坯子插件2024 v3.2.2(支持SketchUp2012-2024版本)安装
    下载链接:https://r0vr8xquwul.feishu.cn/docx/MXC5dUMZroLibaxYgZ3cmkyinDe详细图文教程:https://www.yuque.com/zhefengerhuanzaigua/bld6x5/kc2baq1msy6dehb3软件介绍坯子插件库是为SketchUp(草图大师)用户推出的一款插件管理工具,我们知道在使用sketchup进行模型设计的时候是......
  • 【Microelectronic Systems】期末速通
    PART1嵌入式系统概述与玩转mbed1嵌入式系统,微控制器,与ARM1.1什么是嵌入式系统?微处理器不仅仅存在于通用计算机中,也可以安置在一些不需要计算的设备内部,比如洗衣机,摄像机。微处理器常常可以控制这些产品。因为这类产品的微处理器镶嵌在内部,所以称这类产品为嵌入式系统。......
  • visual studio 插件开发 - 项目介绍
    1.项目结构创建步骤:1.创建名为xxxx的VSIX项目。可以通过搜索“vsix”在“新建项目”对话框中找到VSIX项目模板。2.项目打开时,添加名为FirstCommand的自定义命令项模板。创建好一个vsix项目后最简单的结构:XXXXPackage.cs称为Package类。VisualStudio调用......