文章目录
准备
1、node.js 环境
2、@vue-cli3 脚手架
本示例所用版本为:
- Node.js: 16.13.2
- Electron: 18.3.5
项目搭建
1、创建 vue 项目
自定义选择预装组件: stylus babel typescript router vuex
vue create electron-template
2、添加 electron-builder 打包工具,并选择 electron 版本进行安装
vue add electron-builder

3、运行完成后在src目录下会生成 background.ts 文件(electron入口文件),通过package.json中的"main": "background.js"引入。
package.json 的 scripts 中自动生成electron运行及打包指令

4、更换electron版本(可选)
如果想要更换electron版本,可以重新选择指定版本进行安装
只需将 electron 版本号手动更改为目标版本号后,执行 npm install 重新安装依赖即可,完成后查看当前项目内electron版本号(npm ls electron),可以看到已经更换过来了。


5、运行项目
npm run electron:serve
6、如果运行过程出现的报错及解决方案
①、ts-loader 报错

这是由于 ts-loader 版本过高,在 package-lock.json 中发现当前 ts-loader 版本为 ^9.2.5,只需在 package.json 中固定版本,重新更新依赖,即可成功运行项目

②、Vue Devtools 未成功安装(由于网络问题)

解决方案有两种:
A: 不需要调试工具的情况下,直接将 background.ts 中的引入及引用去掉即可:
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS_DEVTOOLS)
} catch (e: any) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
B: 安装vue-devtools
- 从github克隆vue-devtools:
git clone https://github.com/vuejs/vue-devtools
- 切换到add-remote-devtools分支,默认为main
git checkout add-remote-devtools
- 安装依赖:
npm install
- 修改shells/chrome目录下的manifest.json,将 persistent 的值由 false 改为 true

- 打包:
npm run build
- 最后只需在 background.ts 中引入即可:
import { app, protocol, BrowserWindow, session } from 'electron';
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
session.defaultSession.loadExtension('D:/Project/diy-project/electron-demo/vue-devtools/shells/chrome');
}
createWindow()
})
- 呈现效果:

7、使用 remote 通信
electron V14开始移除了remote,使用的话需要手动安装依赖**
npm install --save @electron/remote
安装好remote之后,我们需要在主进程和渲染进程中进行相应的设置才能使用。
首先是在主程序中引入和初始化remote
// 初始化remote (第一步)
const remote = require("@electron/remote/main");
remote.initialize();
const win = new BrowserWindow({
width: 800,
height: 600,
frame: false,
backgroundColor: '',
webPreferences: {
// 这两个属性需设置 (第二步)
nodeIntegration: true,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
}
})
// 初始化remote (第三步)
remote.enable(win.webContents);
然后在渲染进程中这么使用:
let { BrowserWindow } = require('@electron/remote');
const win = new BrowserWindow({
width:500,
height:500,
})
win.loadFile("page2.html")
2137




被折叠的 条评论
为什么被折叠?



