Electron 是一个使用 JavaScript、HTML 和 CSS 等 Web 技术创建跨平台桌面应用程序的框架。它结合了 Chromium 渲染引擎和 Node.js 运行时,允许开发者构建高质量的桌面应用。下面是一个简要的 Electron 开发教程,从基础到深入,并包括一些常见的报错问题及其解决方案。
Electron 能够使用前端技术栈开发桌面应用,支持 Windows、macOS 和 Linux。其主要特点包括:
安装 Node.js:确保已安装最新版本的 Node.js。
初始化项目:
mkdir my-electron-app && cd my-electron-app
npm init -y
安装 Electron:
npm install electron --save-dev
创建主进程文件(main.js):
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
创建 index.html 文件:
My Electron App
Hello World!
在 package.json 中添加启动脚本:
"scripts": {
"start": "electron ."
}
运行应用:
npm start
将应用拆分为多个文件和模块,可以使代码更易于维护和扩展。例如,我们可以将主进程和渲染进程的逻辑分离,并且还可以为不同的功能创建独立的模块。
示例:分离窗口创建逻辑到单独文件
main.js
(主进程入口)
const { app } = require('electron')
const createWindow = require('./window')
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
window.js
const { BrowserWindow } = require('electron')
let win;
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
})
win.loadFile('index.html')
}
module.exports = createWindow
在 Electron 应用中集成数据库可以帮助存储数据。下面是如何在 Electron 中使用 SQLite 的简单例子。
安装 sqlite3
npm install sqlite3
在主进程中使用
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./mydb.sqlite', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the mydb SQlite database.');
});
db.serialize(() => {
db.run("CREATE TABLE lorem (info TEXT)", (err) => {
if (err) {
console.log("Table already exists.");
} else {
console.log("Table created!");
}
});
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
});
Error: Cannot find module 'electron'
原因:未安装 Electron 或者 node_modules
目录被删除。
解决方案:
npm install electron --save-dev
package.json
文件中是否有正确的依赖项。Not allowed to load local resource
原因:路径配置错误或者安全设置阻止了本地资源的加载。
解决方案:
在 main.js
中确保正确设置了文件路径:
win.loadFile('path/to/your/index.html')
如果使用的是 URL,则需要启用 webSecurity
设置为 false
(不推荐用于生产环境)。
Uncaught ReferenceError: require is not defined
原因:默认情况下,Electron 的渲染进程中禁用了 Node.js 集成。
解决方案:
在创建窗口时启用 Node.js 集成:
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
Unable to access property/method from preload script
原因:当启用了 contextIsolation
但没有正确使用预加载脚本暴露 API 给渲染进程时会发生此问题。
解决方案:
使用预加载脚本来暴露必要的 API:
// preload.js
const { contextBridge } = require('electron');
contextBridge.exposeInMainWorld('myAPI', {
doSomething: () => console.log('Doing something...')
});
在渲染进程中使用暴露的 API:
window.myAPI.doSomething();
错误信息:通常没有明确的错误信息,但可能会观察到窗口尺寸不符合预期或内容显示异常。
原因:可能与屏幕分辨率、DPI 设置或窗口初始化参数有关。
解决方案:
调整窗口大小和位置参数以适应不同的屏幕设置:
win.setSize(800, 600, true); // 最后一个参数表示是否动画化调整大小
错误信息:各种,取决于具体问题,可能是缺少某些依赖或资源文件。
原因:打包工具配置不当,导致必需的文件或依赖缺失。
解决方案:
electron-builder
这样的工具进行更全面的打包管理。EACCES: permission denied
Mixed Content: The page was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint
以上是关于如何在 Electron 应用中进行更深层次开发的一些示例,包括模块化、性能优化以及与第三方服务或库的集成等。。每个部分都可以根据实际需求进一步拓展和定制。