electron+vue3+vite+ts开发中遇到的问题

帮助文档: 简介 | Electron

TypeScript中文网

Vite

Vue3js

1、关于开发环境启动后,窗体程序没有自动启动的问题

因为设置的端口没有触发main.js中设置的是3000,在vite.config.ts中也设置成3000就可以解决

2、关于json文件的读取

1)使用axios请求读取:axios.get("./site_data.json")

注:此方法在打包后会报错

2)使用js读取文件,文件路径要注意path.join(__dirname, '../dist/site_data.json')

不需要有/public,打包后public会没有

我使用的是fs-extra,可以直接读取json文件,不用转换value = JSON.parse(data.toString());
安装:npm install fs-extra
fs.readJson(path, function (e, data) {
fs.writeFile(path, JSON.stringify(data), function (err) {
打包后只能读取,无法写入(可以改变json文件的路径app.asar里面)

3)使用electron-store存储json

安装:npm install electron-store
const Store = require('electron-store');
const db= new Store();
//需要在创建窗口的时候调用初始化方法
  Store.initRenderer();
db.set(json);
db.get("key", value)

3、参数的坑

//跨域警告关闭
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = true;
    fullscreen: true,   // 全屏
    frame: false,   	// 让桌面应用没有边框,这样菜单栏也会消失
    // resizable: false,   // 不允许用户改变窗口大小,
    // autoHideMenuBar: true, // 隐藏菜单栏
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      nodeIntegration: true,// 设置能在页面使用nodejs的API
      contextIsolation: true,// (false时引用的外部地址里js报错;为true时外部的electron无法使用)
      webSecurity: false,//跨域
      backgroundThrottling: false,   // 设置应用在后台正常运行
      enableRemoteModule: true, // 开启remote模块
注意:contextIsolation = true参数,设置后主进程和渲染进程之间的通信方式就要换一种写法

4、ipc通信:主进程和渲染进程

// 主进程向渲染进程通讯
// 1)主进程使用 win.webContents.send 发送消息
// 2)渲染进程使用 ipcRenderer.on 接收消息
// 渲染进程向主进程通信
// 1)渲染进程使用 ipcRenderer.send 或者 ipcRenderer.invoke 发送消息
// 2)主进程使用 ipcMain.on或者ipcMain.handle 接收消息
// 渲染进程向渲染进程
// 1)通过主进程转发 2)数据共享
preload.js中代码
const { contextBridge, ipcRenderer } = require("electron");
//监听通讯
contextBridge.exposeInMainWorld('versions', {
  node: () => process.versions.node,
  chrome: () => process.versions.chrome,
  electron: () => process.versions.electron,
  send: (channel, data) => ipcRenderer.invoke(channel, data),
  // 能暴露的不仅仅是函数,我们还可以暴露变量
渲染进程中的js代码
const test= async () => {
    await window.versions.send("test", "");
test();
main.js中的处理
  ipcMain.handle('setData', (e, data) => {
  })

5、打包问题

1)打开页面是空白,因为不是本地那种http://127.0.0.1/的访问可以直接默认进入配置的路由/的主页,所以需要增加一个路由的跳转

if (NODE_ENV !== 'development') {
    router.push({ path: '/' })
}

2)、路径问题,访问本地文件的地址和跳转的地址

3)、跨域跳转时window.localStorage.getItem('key')值丢失

4)、打包后发现json文件只能读取,不能写入(可能是放到了app.asar里了)

5)、解压.asar后缀的app.asar文件

打开cmd安装asar
npm install -g asar
查看版本后关闭cmd命令