ray-note/web/electron/Electron 初学.md

135 lines
4.4 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

## 安装Electron
- 使用npm初始化一个项目 `npm init`
- 项目内新增`.npmrc` 内容如下
```
# 添加
registry=https://registry.npmmirror.com
#
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
ELECTRON_CUSTOM_DIR={{ version }}
```
- 再使用 `npm install --save-dev electron`, 安装之前先把electron安装失败的cache删除掉
## Electron 打包
ubuntu 安装 `rpmbuild` [参考博客](https://juejin.cn/s/ubuntu%20%E5%AE%89%E8%A3%85rpmbuild)
## Vue3 + Electron
- 使用vite初始化一个`vue-ts` 的项目
- 安装`Electron` 相关的依赖
- `electron`
- `electron-builder`
- `electron-devtools-installer`
- `rimraf`
- [`vite-plugin-electron`](https://github.com/electron-vite/vite-plugin-electron)
- [`vite-plugin-electron-preload`](https://github.com/electron-vite/vite-plugin-electron-preload) 不配置加载preload会失败
- [`vite-plugin-electron-renderer`](https://github.com/electron-vite/vite-plugin-electron-renderer) 目前没有配置相关内容
- 注意:
- 根据vite-plugin-electron 配置项目,并运行即可
- 运行时可能会出现 `electron` 安装失败,把 `node_modules` 删除,删除掉 pnpm的lock yaml和系统的electron的缓存多安装几次这个确实有点烦人
- 使用 `vite-plugin-electron` 之后,还需要使用 `vite-plugin-electron-preload` 才能正确加载preload
## Vue3 + Electron
- 使用`electron-builder` 打包
- 在项目的根目录下创建一个 `electron-builder.json`
```json
{
  "productName": "ElectronViteVue3",
  "appId": "top.rayc.electrontest",
  "copyright": "Copyright © 2024-present Andy",
  "compression": "maximum",
  "asar": true,
  "directories": {
    "output": "release/${version}"
  },
  "nsis": {
    "oneClick": false,
    "allowToChangeInstallationDirectory": true,
    "perMachine": true,
    "deleteAppDataOnUninstall": true,
    "createDesktopShortcut": true,
    "createStartMenuShortcut": true,
    "shortcutName": "ElectronVite4Vue3"
  },
  "win": {
    "icon": "./resource/shortcut.ico",
    "artifactName": "${productName}-v${version}-${platform}-${arch}-setup.${ext}",
    "target": [
      {
        "target": "nsis",
        "arch": ["ia32"]
      }
    ]
  },
  "mac": {
    "icon": "./resource/shortcut.icns",
    "artifactName": "${productName}-v${version}-${platform}-${arch}-setup.${ext}"
  },
  "linux": {
    "icon": "./resource",
    "artifactName": "${productName}-v${version}-${platform}-${arch}-setup.${ext}"
  }
}
```
- 使用 `electron-builder` 命令安装就行
- 注意:
- 在使用 `electron-builder` 打包需要下载几个压缩包,但是下载会失败,可以手动下载这些压缩包,把这些压缩包,保存到 `electron``Cache` 目录中
## Electron 取消顶部菜单栏
- 在 主进程程序中进行修改
- 引入菜单 `Menu`
```TypeScript
import { Menu } from "electron"
```
-`createWindow` 方法中进行设置
```TypeScript
const createWindow = () => {
  Menu.setApplicationMenu(null);
  const win = new BrowserWindow({
    title: "Electron + Vite",
    webPreferences: {
      contextIsolation: false, // 是否开启隔离上下文
      nodeIntegration: true, // 渲染进程使用 Node.js API
      //   sandbox: false,
      preload: path.join(__dirname, "preload.js"), // 预加载脚本
    },
  });
  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
    win.webContents.openDevTools();
  } else {
    // Load your file
    win.loadFile("dist/index.html");
  }
  // 开启调试工具
};
```
## Electron 错误
`Uncaught TypeError: path.join is not a function at node_modules/electron/index.js`
解决办法: [参考博客](https://blog.csdn.net/q1003675852/article/details/134774965)
- 安装 `vite-plugin-optimizer`
-`vite.config.ts` 中配置
```ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import electron from "vite-plugin-electron/simple";
import optimizer from "vite-plugin-optimizer";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    electron({
      main: {
        entry: "electron/main.ts",
      },
      preload: {
        input: "electron/preload.ts",
      },
    }),
    // 加载ipcRenderer
    optimizer({
      electron: `const { ipcRenderer } = require("electron"); export { ipcRenderer};`,
    }),
  ],
});
```