以electron做为基础框架,已经开发两个项目了。第一个项目,我主要负责用react写页面,第二项目既负责electron部分+UI部分。vue
作项目,就是踩坑, 一路作项目,一路踩坑,坑多不可怕,就怕忘记坑。node
开发,固然就须要搭建项目,搭建项目github上有很多模板。react
你能够去 awesome-electron 的 boilerplates部分看到比较流行的模板。
好比:
electron-react-boilerplate
electron-vue
electron-quick-start
electron-boilerplategit
用模板至关于上高速,嗖嗖的飞起,不错的选择。
这些模板基本都是把静态页面和electron部分的开发,集成到一个项目里面,有利有弊。github
咱们项目采用的是分离式的:
electron部分: 负责提供能力,好比读写文件,操做注册表,启动和挂关闭第三方程序,网络拦截,托盘等
UI部分: 绘制页面,必要的时候调用electron封装的能力。web
到这里, electron部分与UI部分的交互,咱们打开窗体的时候,
nodeIntegration是设置为false的,全部的通信都是经过一个所谓的bridge来链接的。typescript
bridge经过preload的属性注入,起到了必定的隔离。npm
咱们项目均采用TS开发
先后端两个项目都是基于TS开发,好处不用说。
问题在于,如何将bridge部分友好的提供给UI部分。
也很简单,typescript 编译的时候,其实有一个declaration的选项。
基于bridge单独起一个配置文件,里面仅仅include须要的文件,执行build的,再拷贝到UI项目里面,UI项目就能获得友好的提示。json
electron-better-ipc 是不错的选择,原理就是利用EventEmitter的once特性,内部的每次通信都是一个新的事件类型。
对于超时和错误捕捉,主向多个渲染进程发消息,都还得本身去加强。后端
咱们是本身维护了一个调用信息, 发送的数据有一个key来标识,目前看来,还算稳定。
electron-log是不错的选择,简简单单的就能记录主进程和渲染进程的日志。
可是不能记录node唤起的子进程的日志,真要想记录,子进程单独通知到外面,外面记录。或者单独本身弄一个写子进程的日志也没问题的。
日志多了确定不行,就会有日志轮转。目前这个库,好像有一个简单粗暴的轮转策略,确定是不够用的。
具体的能够到File transport
function archiveLog(file) { file = file.toString(); const info = path.parse(file); try { fs.renameSync(file, path.join(info.dir, info.name + '.old' + info.ext)); } catch (e) { console.warn('Could not rotate log', e); } }
我这里就贴一段基本可用的, deleteFiles
自定去实现,你能够保留几个文件,保留几天的文件,都是能够的。
// 50M log.transports.file.maxSize = 50 * 1024 * 1024; log.transports.file.archiveLog = function archiveLog(file: string) { file = file.toString(); const info = path.parse(file); try { // 重命名 const dateStr = getDateStr(); const newFileName = path.join(info.dir, `${info.name}.${dateStr}${info.ext}`); console.log("archiveLog", file, newFileName); fs.renameSync(file, newFileName); // 删除旧文件 deleteFiles(info.dir) } catch (e) { console.error('Could not rotate log', e); } }
electron-store 很不错。
咱们采用的是内存数据 + config.json的模式,实际上本质没变。
若是是窗体之间的页面之间要共享数据,其实用localStorage和sessionStorage,indexedDB都是不错的选择。
简单的排查顺序
1.浏览器打开网页地址
2.若是不能打开, 查看网络是否正常
3.网络正常,ping域名
4.ping 不通, 说明域名有问题
5.打开 %appdata%, 查看日志是否是有打开页面超时的提示
6.关闭 360安全卫士,从新打开主播端
最后一条是关键哈。
不签名,不过百的状况下,升级启动都极可能被360拦截。
build时指定electron版本,headers头文件路径
https://www.electronjs.org/docs/tutorial/using-native-node-modules
这个官方是有很明确的指出来的
使用npm 安装,不用cnpm。
这是和不一样的安装方式,文件目录结构不一致。
固然开发的时候,你是可使用cnpm或者yarn的。
我没有尝试使用打包作一些修改让cnpm有效,大家要是知道,能够留言告诉我哈。
这个和上面那个有点相似,可是又不同的。 下面这种状况多是.node模块须要引用一些dll文件,却没有。好比常见的msvcr120.dll,msvcr110.dll,msvcp120.dll,msvcp110.dll这些文件,你把这些放到.node的同级目录。至于怎么区分32位和64位,哈哈,我知道您懂。
AppData\Local\Temp\xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.tmp.node
https://stackoverflow.com/questions/41253450/error-the-specified-module-could-not-be-found
有提到大体的原生就是 .node缺乏一些dll库。可使用 http://www.dependencywalker.com/ 检查缺乏啥
我作了四种尝试:
后两种是有效的,并且这个问题可能只出如今某些机器上。某些机器是正确的,某些机器却不正确。
首先说这个发布者是哪一个字段,实际上是package.json里面的author字段的name属性,固然能够有多种写法。
若是的你名字相似 牛潮(北京)有限公司
,那么你打包出来就只会剩下 牛潮
两个字,是否是有一些神奇。
这个实际上是 electron-builder库packages\app-builder-lib\src\util\normalizePackageData.ts 或者额是 normalize-package-data库作了一些操做。
unParsePerson以后再parsePerson,英文括弧后面的东西就没了。怎么办,我如今是手动找到修改一下。
function fixPeople(data: any) { modifyPeople(data, unParsePerson) modifyPeople(data, parsePerson) }, function unParsePerson (person) { if (typeof person === "string") return person var name = person.name || "" var u = person.url || person.web var url = u ? (" ("+u+")") : "" var e = person.email || person.mail var email = e ? (" <"+e+">") : "" return name+email+url } function parsePerson (person) { console.log("parsePerson person", person) if (typeof person !== "string") return person var name = person.match(/^([^\(<]+)/) var url = person.match(/\(([^\)]+)\)/) var email = person.match(/<([^>]+)>/) var obj = {} if (name && name[0].trim()) obj.name = name[0].trim() if (email) obj.email = email[1]; if (url) obj.url = url[1]; return obj }
他这个打包能够签名,可是要你提供.pfx文件和密码。
这就有点老火了,公司的这两个东西通常不会轻易给你。
要么大家有统一的打包中心,那就没问题。
惋惜咱们公司只有统一的签名中心,签名以后,exe文件是有变化的,好比大小和最后修改时间,这就会致使更新的时候,检查hash值会失败。
问题不大:
基本就是这样啦。
这里送一段基本能用的代码吧:
import { createHash } from "crypto" import { createReadStream, statSync , readFileSync, writeFileSync } from "fs" import path from "path"; import YAML from "yaml"; const jsonConfig = require("../package.json"); const version = jsonConfig.version; const exeFilePath = path.join(__dirname, `../packages/${version}.exe`); const yamlFilePath = path.join(__dirname, "../packages/latest.yml"); const jsFilePath = path.join(__dirname, "../packages/latest.js"); const bakYamlFilePath = path.join(__dirname, `../packages/latest.bak.yml`); // packages\app-builder-lib\src\util\hash.ts function hashFile(file: string, algorithm = "sha512", encoding: "base64" | "hex" = "base64", options?: any): Promise<string> { return new Promise<string>((resolve, reject) => { const hash = createHash(algorithm) hash.on("error", reject).setEncoding(encoding) createReadStream(file, { ...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */ }) .on("error", reject) .on("end", () => { hash.end() resolve(hash.read() as string) }) .pipe(hash, { end: false }) }) } function getFileSize(path: string){ const state = statSync(path); return state.size; } function getYAML(path: string){ const file = readFileSync(path, 'utf8') const data = YAML.parse(file); return data; } function saveYAML(path:string, content: any){ writeFileSync(path, YAML.stringify(content)) } function saveJS(path:string, content: string){ writeFileSync(path, content) } ;(async function updateLatestYML(){ try{ const hash = await hashFile(exeFilePath); const size = getFileSize(exeFilePath); console.log("hash:", hash); console.log("size:", size); const yamlData = getYAML(yamlFilePath); saveYAML(bakYamlFilePath, yamlData); console.log("yamlData:before", yamlData); const name = `${version}.exe` yamlData.version = version; const file = yamlData.files[0]; file.url = name; file.sha512 = hash; file.size = size; yamlData.path = name; yamlData.sha512 = hash; console.log("yamlData:after", yamlData); saveYAML(yamlFilePath, yamlData); saveJS(jsFilePath, `window._lastest=${JSON.stringify(yamlData)}`); }catch(err){ console.log("update latest.yml 失败", err); } })();
https://www.electron.build/auto-update#debugging
https://stackoverflow.com/questions/51003995/how-can-i-test-electron-builder-auto-update-flow
https://github.com/electron-userland/electron-builder/issues/3053#issuecomment-401001573
虽然官方建议单独使用一个啥server来着,总让人以为有点复杂,其实仍是能够直接在开发中测试的。
代码层面作一点小修改
function checkUpdate() { // 开发环境 if(!app.isPackaged){ return autoUpdater.checkForUpdates(); } return autoUpdater.checkForUpdatesAndNotify(); }
这里还要额外注意
%localappdata%/{默认是package.json里面name}-updater/pending
,和electron-builder里面的是指有关你想一想,咱们不少时候打开的是远程的网页地址。 若是返回的状态码是404,明显不是咱们想要的,若是咱们依据did-fail-load事件去判断,是否加载失败,固然是不知足咱们的需求的。
咱们须要在远程加载失败的时候,使用本地的默认页面去给用户一些提示信息,以及能够关闭窗体。
这个时候就要did-frame-navigate
出场,根据httpResponseCode
的状态去使用本地备用页面了。
win.webContents.on("did-frame-navigate", (event: Electron.Event, url: string, httpResponseCode: number, httpStatusText: string, isMainFrame: boolean, frameProcessId: number, frameRoutingId: number) =>{ console.log("did-frame-navigate", httpResponseCode, httpStatusText); if(httpResponseCode >= 400 && !this.isUsedFailedPage){ return this.useFailedPage(); } });
ctrl + r
刷新页面
ctrl + shift + i
打开开发者工具
哈哈,要是不当心被用户打开是否是有点搞笑了。
你能够写一个配置到配置文件,默认不容许打开,当须要去现场排查问题的时候,能够打开。 被打开确定有危险,可是方便调试。
我这里作的页面拦截
const BLACK_LIST = ["KeyI", "KeyR"]; function preventForceRefreshAndTool() { const env = process.env.ENV; console.log("process.env.ENV", process.env.ENV); if (env !== "prod") { return console.log("非产线环境,容许刷新和打开开发者工具"); } window.addEventListener('keydown', (e: KeyboardEvent) => { const { ctrlKey, code, shiftKey } = e; console.log("keydown", e); // ctrl + r // crtl + shift + i if (ctrlKey && shiftKey && BLACK_LIST.includes(code)) { console.log("globalShortcut:被阻止", ctrlKey, shiftKey, code); e.preventDefault(); } }, false); }
electron拦截
win.webContents.on('before-input-event', (event, input) => { console.log('before-input-event', input.control, input.shift, input.key) if (input.control && KEY_BLACK_LIST.includes(input.key.toUpperCase())) { event.preventDefault() } });
到这里,老板已经走到个人身后,我默默的说,我总结一下问题。
老板说: 好样子的,不过你为嘛在上班时间写博客。
我: 流汗,各位,拜。
排查问题
其余工具类