发布于 2026-01-06 2 阅读
0

使用 Vue.js 构建一个简单的 Electron 应用 🚀🔧

使用 Vue.js 构建一个简单的 Electron 应用 🚀🔧

使用 Vue.js 构建一个简单的 Electron 应用 🚀🔧

Electron 允许开发者使用 Web 技术构建跨平台桌面应用程序。在本教程中,我们将逐步讲解如何使用 Vue.js 框架创建一个基本的 Electron 应用程序。教程结束时,您将掌握开发利用 Vue.js 强大功能的桌面应用程序的扎实基础。

1.初始化你的 Vue.js 项目

首先使用 Vue CLI 创建一个新的 Vue.js 项目。如果您尚未安装 CLI,可以使用以下命令进行安装:

npm install -g @vue/cli
Enter fullscreen mode Exit fullscreen mode

现在,创建一个新的 Vue 项目:

vue create vue-electron-app
Enter fullscreen mode Exit fullscreen mode

按照提示配置您的项目。

2.在您的项目中安装 Electron

进入你的 Vue 项目目录,并将 Electron 安装为开发依赖项:

cd vue-electron-app
npm install --save-dev electron
Enter fullscreen mode Exit fullscreen mode

3.创建 Electron 主文件

main.js在项目根目录下创建一个名为 `.electron.js` 的文件。该文件将作为 Electron 的入口点:

// main.js
const { app, BrowserWindow } = require('electron');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
  });

  mainWindow.loadFile('dist/index.html'); // Adjust the path based on your build directory

  mainWindow.on('closed', function () {
    mainWindow = null;
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', function () {
  if (mainWindow === null) createWindow();
});
Enter fullscreen mode Exit fullscreen mode

4.更新您的 Vue 项目配置

修改你的代码package.json,使其包含 Electron 特有的脚本并配置构建目录:

// package.json
{
  // ...
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build && electron .",
    // Add other scripts as needed
  },
  "main": "main.js",
  // ...
}
Enter fullscreen mode Exit fullscreen mode

5.构建并运行您的 Electron 应用程序

使用以下命令构建并运行您的 Electron 应用程序:

npm run build
Enter fullscreen mode Exit fullscreen mode

这将构建您的 Vue.js 项目并启动 Electron 应用程序。

结论:Vue.js + Electron = 桌面魔法🚀🔧

恭喜!您已成功使用 Vue.js 构建了一个简单的 Electron 应用。这种组合为使用熟悉的 Vue.js 框架创建桌面应用开启了无限可能。您可以进一步探索,添加功能,并根据您的桌面开发需求定制应用。祝您使用 Vue.js 和 Electron 编码愉快!🌐✨

文章来源:https://dev.to/amatisse/building-a-simple-electron-application-with-vuejs-52aa