如果可以实现记得点赞分享,谢谢老铁~
Electron是一个使用 JavaScript、HTML 和 CSS 构建桌面应用程序的框架。 Electron 将 Chromium 和 Node.js 嵌入到了一个二进制文件中,因此它允许你仅需一个代码仓库,就可以撰写支持 Windows、macOS 和 Linux 的跨平台应用。
一.准备工作
1.确保已在您的开发环境中安装了 Node.js 和 npm(Node.js 包管理器)。
2.创建一个新的文件夹(js_demo),进入该文件夹,并在命令行中运行以下命令,以初始化一个新的 Node.js 项目:
npm init -y
3.然后,在项目文件夹中安装 Electron 依赖:
npm install electron
二.创建文件
4.在项目文件夹中创建一个新的 index.js 文件,将以下代码复制到该文件中:
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
    // 创建一个新的浏览器窗口
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true
        }
    });
    // 加载 index.html 文件
    win.loadFile(path.join(__dirname, 'index.html'));
    // 打开开发者工具
    win.webContents.openDevTools();
}
// 当 Electron 初始化完成并准备创建浏览器窗口时调用
app.whenReady().then(createWindow);
// 当所有窗口关闭时退出应用
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});
// 在 macOS 上,单击应用程序的 dock 图标并且没有其他窗口打开时,重新创建一个窗口
app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});
 
5.在项目文件夹中创建一个新的 index.html 文件,并将以下代码复制到该文件中:
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Electron App</title>
</head>
<body>
  <button id="myButton">点击我</button>
  <script src="index.js"inde></script> <!-- 添加对 index.js 文件的引用 -->
  <script>
    // 获取按钮元素
    var button = document.getElementById('myButton');
    // 添加点击事件处理程序
    button.addEventListener('click', function() {
      alert('按钮被点击了!');
    });
  </script>
</body>
</html>
 
三.运行
6.最后,在命令行中运行以下命令以启动 Electron 应用程序:
npx electron .
这将启动 Electron 应用程序并显示一个桌面窗口,其中包含一个按钮。当按钮被点击时,会弹出一个框。
这里的目录结构目前是:
 
四.目录及效果
这里是效果图:
 
到这里呢,你就成功的运行起来一个简单的桌面应用程序了。
 但你肯定有个疑问,怎么没有生成一个桌面应用呢?
请看下一篇 electron之纯原生js/jquery的桌面应用程序(应用生成)



















