如何利用 Electron 快速開發(fā)一個(gè)桌面端應(yīng)用

我是把現(xiàn)有的一個(gè)vue3項(xiàng)目打包到桌面端的,也可以新建一個(gè)項(xiàng)目。

第一步、準(zhǔn)備工作

1.打開項(xiàng)目終端輸入yarn add electron,安裝 electron
2.安裝依賴wait-on以及cross-env,yarn add wait-on --devyarn add cross-env --dev

第二步、項(xiàng)目根目錄下新建main.js文件

const { app, BrowserWindow } = require('electron');
const path = require('path');
const NODE_ENV = process.env.NODE_ENV;
app.commandLine.appendSwitch('allow-file-access-from-files');
function createWindow() {
    console.log('Creating main window...');
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 980,
    height: 680,
    fullscreen: true,
    skipTaskbar: true,
    autoHideMenuBar: true, // 是否自動(dòng)隱藏菜單欄
    webPreferences: {
      nodeIntegration: true,
     contextIsolation: false, // 同上,根據(jù)需要調(diào)整
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  if (NODE_ENV === 'development') {
    console.log('Loading development URL...');
    mainWindow.loadURL('http://localhost:3001/');//替換為你的本地地址
    mainWindow.webContents.openDevTools();
  } else {
    console.log('Loading production file...');
   // mainWindow.loadURL(`file://${path.join(__dirname, '../dist/index.html')}`);
   mainWindow.loadFile('dist/index.html'); // 確保路徑正確指向你的 HTML 文件
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.

app.whenReady().then(() => {
  createWindow();
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

第三步、項(xiàng)目根目錄下新建 preload.js文件

//允許vue項(xiàng)目使用 ipcRenderer 接口, 演示項(xiàng)目中沒有使用此功能
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('ipcRender', ipcRenderer);

第四步、修改package.json

1.新增

"main": "main.js",

2.在scripts中新增

"electron:dev": "wait-on tcp:3000 && cross-env NODE_ENV=development electron ./","electron:build": "rimraf dist &&  vite build &&  electron-builder",
    "electron:build2": "electron-builder"

3.刪除

"type":"module"

4.新增

"build": {
    "productName": "webim-electron",
    "appId": "com.lvais",
    "copyright": "2023@easemob",
    "directories": {
      "output": "output"
    },
    "extraResources": [
      {
        "from": "./src/assets",
        "to": "./assets"
      }
    ],
    "files": [
      "dist/**/*",
      "electron/**/*",
      "main.js"
    ],
    "mac": {
      "artifactName": "${productName}_${version}.${ext}",
      "target": [
        "dmg"
      ]
    },
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": [
            "x64"
          ]
        }
      ],
      "artifactName": "${productName}_${version}.${ext}"
    },
    "nsis": {
      "oneClick": false,
      "allowElevation": true,
      "allowToChangeInstallationDirectory": true,
      "createDesktopShortcut": true
    },
    "linux": {}
  }

第五步、修改vite.config.js

vite.config.js里面配置

 base: "./",
  build:{
    outDir: 'dist',
    assetsDir: 'assets',
  },

第六步、router下面index.js修改,改為哈希模式

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

第七步、啟動(dòng)項(xiàng)目

1.啟動(dòng)運(yùn)行原 vue 項(xiàng)目yarn dev
2.新開一個(gè)終端執(zhí)行,輸入下方命令啟動(dòng) electron yarn run electron:dev

第八步、下載electron 打包工具庫(kù)electron-builder,啟動(dòng)項(xiàng)目

1.yarn add electron-builder --dev
2.build 原始 vue 項(xiàng)目:yarn run build
3.build electron 項(xiàng)目:yarn run electron:build

這樣目錄下會(huì)自動(dòng)生成output文件,打開之后可以選擇雙擊打開軟件驗(yàn)證看下是否可以正常開啟應(yīng)用

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容