一、主进程调试(Main)
主进程因为运行在NodeJS环境中,本身没有显示界面可以直观调试程序,不过按照官方的文档说明,Electron主进程可以利用VSCode进行调试。调试前首先得先创建electron应用(本文省略)。
1.Electron应用配置
在electron应用根目录创建.vscode/launch.json
,代码为
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args" : ["."]
}
]
}
2.VSCode启动
VSCode打开Electron应用目录,点击左侧“运行和调试”工具,选择Debug Main Process
进行启动。Main进程运行过程中的输出将会在VSCode调试控制台看到结果。
二、渲染进程调试(Render)
渲染进程因为运行在chromium内核中,因此可以使用chromium开发者工具进行调试,具体在主进程中设置开启开发者工具。
main.js
在创建窗体时添加代码mainWindow.webContents.openDevTools()
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
mainWindow.webContents.openDevTools()
}
app.whenReady().then(() => {
createWindow()
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})