一、问题描述
公司开发了很久的web项目(Vue框架),由于打印问题,现在需要做成本地应用,所以需要将web应用转为本地应用(重新开发成本太高,老板也不同意的嘛),这个时候就想到了Electron开发桌面应用
二、Electron简介
Electron是由Github开发的开源框架,它允许开发者使用web技术构建平台的桌面应用。像VSCode、Atom、Slack都是使用Electron进行开发的
Electron的使用场景
- 1.没有专门的桌面应用开发人员,需要前端进行兼顾开发
- 2.一个应用同时需要web端和桌面端的
- 3.开发一些效率工具,比如API类的工具
三、使用过程
- 1.安装Electron开发环境依赖(需要下载electron-xxx.zip,速度可能会慢些)
npm install electron --save-dev
// 国内网络下载electron可能很慢,建议设置
npm config set registry https://registry.npm.taobao.org/
npm config set ELECTRON_MIRROR http://npm.taobao.org/mirrors/electron/
- 2.在
package.json
同级加上文件electron.js
//electron.js
// 主进程
// Modules to control application life and create native browser window
const {app, protocol, Menu, BrowserWindow } = require('electron')
const path = require('path')
const { readFile } = require ('fs')
const { URL } = require ('url')
// 处理文件打包之后的访问路径为 app的相对路径,
function createProtocol(scheme) {
protocol.registerBufferProtocol(
scheme,
(request, respond) => {
let pathName = new URL(request.url).pathname
pathName = decodeURI(pathName) // Needed in case URL contains spaces
readFile(path.join(__dirname, pathName), (error, data) => {
if (error) {
console.error(`Failed to read ${pathName} on ${scheme} protocol`, error)
}
const extension = path.extname(pathName).toLowerCase()
let mimeType = ''
if (extension === '.js') {
mimeType = 'text/javascript'
} else if (extension === '.html') {
mimeType = 'text/html'
} else if (extension === '.css') {
mimeType = 'text/css'
} else if (extension === '.svg' || extension === '.svgz') {
mimeType = 'image/svg+xml'
} else if (extension === '.json') {
mimeType = 'application/json'
}
respond({ mimeType, data })
})
},
error => {
if (error) {
console.error(`Failed to register ${scheme} protocol`, error)
}
}
)
}
// 防止 localStorage 不可访问
protocol.registerSchemesAsPrivileged([{
scheme: 'app',
privileges: {
secure: true,
standard: true
}
}])
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let template = [] //顶部菜单模板
function createWindow () {
// Create the browser window. 桌面应用的初始宽度、高度
mainWindow = new BrowserWindow({
width: 1600,
height: 1000,
})
// and load the index.html of the app.
createProtocol('app') // 创建一个应用,访问路径的初始化
mainWindow.loadURL('app://./index.html') // 入口文件, 窗口指向 index.html 文件作为首页,这里可以是vue,react,angular 的打包之后的dist目录内部的index.html文件。
// Open the DevTools.
// mainWindow.webContents.openDevTools()
let menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu) // 重新设置桌面应用的顶部菜单
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) createWindow()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
- 3.在
package.json
中添加指令,用于启动Electron桌面应用
"electron-dev": "vue-cli-service build && electron electron.js",
"electron-build": "electron-packager ./dist/ --arch=x64 --icon=logo.ico --overwrite"
四、注意点
// 添加logo.ico图标到根目录
- 1.在
vue.config.js
中webpack的基础配置文件里的module.exports内部添加一条数据publicpath: './'
: 这里是为了让build之后的文件引用相对路径 - 2.先
npm run electron-dev
,可以运行开发中的electron桌面应用
打包桌面应用,这里使用的打包工具是electron-packager
- 3.安装
electron-packager
npm install electron-packager --save-dev
- 4.复制
package.json
到dist文件夹下,新增一条数据"main":"electron.js"
- 5.复制electron.js到dist文件里
- 6.执行
npm run electron-build
,便会生成安装包文件
步骤总结
- 1.
npm run electron-dev
生成dist文件夹 - 2.复制
package.json
到dist文件夹下,新增一条数据"main":"electron.js"
- 3.复制electron.js到dist文件里
- 4.
npm run electron-build
五、问题解决
- 1.打包出来.exe的应用运行后页面空白
解决方法:1. 检查路由模式 2. 检查文件引用相对路径 3. 检查自己的地址
- 2.运行后页面不能跳转(页面地址请求正常)
解决方法:个人项目原因,项目token验证,token放在cookies中,在封装的桌面应用中,cookies没塞进去,导致路由跳转token校验失败