

在本技术博客中,我们将探讨如何使用 Electron 框架创建一个简单的待办事项(To-Do List)应用程序。此项目适合那些想要学习如何结合 HTML、CSS 和 JavaScript 来构建跨平台桌面应用程序的开发者。
首先,确保你已经安装了 Node.js 和 npm。接下来,打开终端并运行以下命令来初始化你的项目:
mkdir todo-app
cd todo-app
npm init -y然后安装 Electron:
npm install electron --save-dev建立如下的文件夹和文件结构:
todo-app/
├── main.js
├── index.html
├── renderer.js
└── package.json1. main.js
这是 Electron 应用程序的入口点,负责创建窗口和管理应用生命周期事件。
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'renderer.js')
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});2. index.html
这是你的应用的主要界面,用户将与之交互以添加或删除待办事项。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<h1>我的待办事项</h1>
<input type="text" id="new-todo" placeholder="添加新任务...">
<button id="add">添加</button>
<ul id="todos"></ul>
</div>
<script src="renderer.js"></script>
</body>
</html>3. renderer.js
这个脚本控制着你的应用的业务逻辑,比如添加或删除待办事项。
document.getElementById('add').addEventListener('click', () => {
const todoText = document.getElementById('new-todo').value;
if (todoText.trim()) {
const li = document.createElement('li');
li.textContent = todoText;
li.addEventListener('click', () => {
li.remove();
});
document.getElementById('todos').appendChild(li);
document.getElementById('new-todo').value = '';
}
});
现在,你应该能看到一个简单的 To-Do List 应用程序,允许用户添加和点击删除待办事项。

通过本文,我们学习了如何从头开始创建一个基本的待办事项应用程序使用 Electron。尽管这是一个非常基础的例子,但它为构建更复杂的应用打下了良好的基础。希望这能激发你进一步探索 Electron 的潜力!