Electron 客户端程序在开发时不同于一般网页开发,程序的生命周期也是不一样的,一般需要经历开发、测试、打包构建、分发程序、收集反馈等。
这里介绍一些技巧, 可以方便在开发、测试及发布后更好地调试。
C:\Windows\xxx, 而Mac和Linux下是/var/www。在处理时最好使用path.resolve()处理一下。
Command按键
// Disable error dialogs show
dialog._showErrorBox = dialog.showErrorBox
dialog.showErrorBox = function (title, content) {
global.logger(title + '\n' + content)
}
推荐一款比较好用的插件electron-log。默认的日志记录位置是:
~/.config/<app name>/log.log
~/Library/Logs/<app name>/log.log
%USERPROFILE%\AppData\Roaming<app name>\log.log
另外,我们也可以同步页面(renderer process)中的console日志:
// sync logs
const logger = remote.require('electron-log')
window.logger = logger
const proxyLog = (target, dest) => {
const original = console[target]
console[target] = (...args) => {
logger[dest](...args)
original(...args)
}
}
proxyLog('log', 'info')
proxyLog('info', 'info')
proxyLog('warn', 'warn')
proxyLog('error', 'error')
这样便可以统一日志输出,方便搜集。
我们可以使用Electron提供的Accelerator,设置一个较复杂,用户不容易按的组合快捷键:
import { app globalShortcut } from 'electron'
app.on('ready', () => {
globalShortcut.register('CmdOrCtrl+Alt+Shift+F11', () => {
mainWindow.webContents.openDevTools()
})
})
另外一种添加更复杂快捷键的方式是通过Mousetrap 这个模块。
// bind keys
import Mousetrap from 'mousetrap'
import {
remote,
ipcRenderer as ipc
} from 'electron'
// open devtools in production for debug
Mousetrap.bind('d e b u g enter', () => {
ipc.send('open-devtools')
})
在main中接收ipc消息,打开devtool即可。
推荐两个插件:
用法也很简单,在renderer中执行:// support copy, paste, cut and etc.
// with shortcut and context menu
const inputMenu = require('electron-input-menu')
const context = require('electron-contextmenu-middleware')
inputMenu.registerShortcuts();
context.use(inputMenu)
context.activate()
用法很简单:
import {machineId, machineIdSync} from 'node-machine-id';
// Asyncronous call with async/await or Promise
async function getMachineId() {
let id = await machineId();
...
}
machineId().then((id) => {
...
})
// Syncronous call
let id = machineIdSync()
// id = c24b0fe51856497eebb6a2bfcd120247aac0d6334d670bb92e09a00ce8169365
let id = machineIdSync({original: true})
// id = 98912984-c4e9-5ceb-8000-03882a0485e4
在程序第一次启动时获取,然后把它缓存起来。
配置会以文件形式保存在程序目录中,可以通过app.getPath('userData')获得目录路径。