版本
- Electron@16.0.0
- Node@14.5.0
1. 使用vue-cli创建vue3项目
全局安装vue-cli
npm install -g @vue/cli
安装成功后创建项目,vue选择3.0版本
vue create my-app
创建成功后,进入项目路径my-app,运行命令 npm run serve
,启动项目
集成组件库Element Plus
npm install --save element-plus
// src/main.js
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
createApp(App)
.use(ElementPlus)
.mount('#app')
也可以按需导入
在页面上加一个button
2. 使用Electron启动
2.1 安装electron,npm install --save-dev electron@version
安装失败的话,可以参考文档进行离线安装
2.2 安装成功后,在项目根目录创建main.js文件,并且将package.json中的main字段改为"main.js"
// main.js
const path = require('path')
const { app, BrowserWindow } = require('electron')
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadURL(`file://${__dirname}/dist/index.html`);
win.webContents.openDevTools();
}
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
2.3 npm run build
打包前端项目,打包后会生成dist文件夹,
然后用electron启动应用,注意main.js中的 win.loadURL(file://${__dirname}/dist/index.html
);
npx electron .
发现electron启动后所有静态文件加载失败,这是因为打包后的文件是绝对路径,以/开头
查看Vue CLI相关文档后,发现可以用publicPath字段将打包后的资源文件路径改为相对路径, 在根目录下新建vue.config.js
// vue.config.js
module.exports = {
publicPath: './',
configureWebpack: {
}
}
publicPath默认为"/", 修改为"./"相对路径
再重新运行 npm run build && npx electron .
这样就加载正常了,所有资源文件就变成相对路径了
3. electron实现开发环境的热更新
如果想实时在electron中预览页面效果,可以 安装 electron-reloader
npm install --save-dev electron-reloader
修改main.js, 增加require('electron-reloader')(module)
// main.js
...
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
try {
require('electron-reloader')(module)
}catch(e){}
关键将main.js的 loadURL改为
win.loadURL(`http://localhost:8081`);
// win.loadURL(`file://${__dirname}/dist/index.html`);
http://localhost:8081 是npm run serve
启动项目的地址。
打开一个终端运行npm run serve
实时监听前端代码的修改,再打开一个终端运行 npx electron .
运行应用,这样修改前端代码(渲染进程)或者 main.js(主进程)electron窗口都会实时更新
4. 组件中使用electron相关的api 运行后会报错
需要将webpack的target 字段修改为electron-renderer,webpack相关文档
// vue.config.js
module.exports = {
publicPath: './',
configureWebpack: {
target: 'electron-renderer'
}
}
重新启动应用,不报上图中的错误了,又出现另一个错误 Uncaught ReferenceError: require is not defined
因为安全性,在electron的渲染进程中不允许使用require除非nodeIntegration
是 true
并且 contextIsolation
是 false
.
官方文档
// main.js
...
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
// preload: path.join(__dirname, 'preload.js')
}
})
...
应用运行成功,不再报错了