create-vue創(chuàng)建vue3項目并集成electron

create-vue搭建項目

官網(wǎng):https://staging-cn.vuejs.org/guide/quick-start.html#with-build-tools

create-vue 是 Vue3 的專用腳手架,使用 vite 創(chuàng)建 Vue3 的項目,也可以選擇安裝需要的各種插件,使用更簡單。

  1. 使用方法:
    npm init vue@latest

  2. 可選插件:

? Project name: … <your-project-name>
// TypeScript的支持
? Add TypeScript? … No / Yes
// JSX的支持
? Add JSX Support? … No / Yes
// 支持路由
? Add Vue Router for Single Page Application development? … No / Yes
// 狀態(tài)管理
? Add Pinia for state management? … No / Yes
// Vitest測試框架
? Add Vitest for Unit testing? … No / Yes
// Cypress E2E測試工具
? Add Cypress for both Unit and End-to-End testing? … No / Yes
// ESLint代碼格式化規(guī)范檢查
? Add ESLint for code quality? … No / Yes
// Prettier代碼格式化
? Add Prettier for code formatting? … No / Yes
  1. 啟動項目:
> cd <your-project-name>
> npm install
> npm run dev

注意:運行報錯,npm和node都要是最新版本

  1. 當準備將應用發(fā)布到生產(chǎn)環(huán)境時,運行:
> npm run build

至此vue3搭建完成,下面開始集成electron

這里我的vue3+vite項目已經(jīng)有了,在這基礎(chǔ)上使用electron轉(zhuǎn)換成桌面應用。

1.獲取electron配置文件
首先可以執(zhí)行以下命令,從electron的官網(wǎng)下載案例,下載會比較慢,可以直接訪問git倉庫,下載代碼。

git clone https://github.com/electron/electron-quick-start
下載以后主要是要用到代碼里的main.js和preload.js兩個文件。如果不下載,直接復制下面的兩個文件代碼即可。

image.png

main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// 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()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) 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()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

preload.js

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

把以上兩個文件放到自己的vue項目文件目錄下
在根目錄下新建了一個electron文件夾,里面放兩個js文件


image.png

2、項目配置
安裝依賴

electron不多說。concurrently和 wait-on解釋一下。
開發(fā)環(huán)境的運行條件是,先運行vite啟動服務,然后electron去加載本地服務url。這里需要安裝兩個依賴。

concurrently:阻塞運行多個命令,-k參數(shù)用來清除其它已經(jīng)存在或者掛掉的進程
-wait-on:等待資源,此處用來等待url可訪問

npm install electron --save-dev
npm install concurrently wait-on --save-dev

electron/main.js
根據(jù)需求,我添加了Menu.setApplicationMenu(null)隱藏菜單欄,frame是否展示頂部導航的配置,默認為true。mainWindow.loadFile(‘index.html’)修改成了mainWindow.loadURL(關(guān)鍵),具體配置如下。

// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')

//這里的配置手動寫的,也可以使用cross-env插件配置
const mode = 'development'

/*隱藏electron創(chuàng)聽的菜單欄*/
Menu.setApplicationMenu(null)

function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        frame: true /*是否展示頂部導航  去掉關(guān)閉按鈕  最大化最小化按鈕*/ ,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
        },
    })

    // and load the index.html of the app.
    // mainWindow.loadFile('index.html')  修改成如下

    mainWindow.loadURL(mode === 'development' ? 'http://localhost:2103' : `file://${path.join(__dirname, '../dist/index.html')}`)

    // Open the DevTools.
    if (mode === 'development') {
        mainWindow.webContents.openDevTools()
    }
}

// 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()

    app.on('activate', function() {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) 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()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

3.vite.config.js

配置base: ‘./’

image.png

4.package.json

main:main.js修改成main:electron/main.js。添加electron和electron:serve指令

    "main": "electron/main.js",
    "scripts": {
        "dev": "vite --host",
        "serve": "vite preview",
        "build": "vite build",
        "electron": "wait-on tcp:2103 && electron . --mode=development ",
        "electron:serve": "concurrently -k \"npm run dev\" \"npm run electron\""
    },

運行項目
npm run electron:serve

1.如果運行不成功或者成功之后白屏,可查看以下幾個關(guān)鍵配置

端口一致


image.png

electron熱更新

electron可以使用electron-reloader這個依賴實現(xiàn)項目熱更新:更改html/js/css代碼框架自動更新,大大提高開發(fā)效率,不用每次都npm start重新啟動。

1.安裝electron-reloader依賴

npm install --save-dev electron-reloader
2.程序入口文件(一般是index.js)中加入以下代碼

// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')

//這里的配置手動寫的,也可以使用cross-env插件配置
const mode = 'development'

/*隱藏electron創(chuàng)聽的菜單欄*/
// Menu.setApplicationMenu(null)


//熱加載 以下為增加部分
try {
  require('electron-reloader')(module,{});
} catch (_) {}


function createWindow() {

重啟一下項目就可以了。

3、打包生成桌面應用

1.安裝打包插件 electron-builder
npm install electron-builder --save-dev
2.package.json添加electron:build命令,和build配置

    "main": "electron/main.js",
    "scripts": {
        "dev": "vite --host",
        "serve": "vite preview",
        "build": "vite build",
        "electron": "wait-on tcp:2103 && electron . --mode=development ",
        "electron:serve": "concurrently -k \"npm run dev\" \"npm run electron\"",
        "electron:build": "npm run build && electron-builder"
    },
     "build": {
        "appId": "8a06282fb08c48eeacb15bfbe4d3a35b",
        "productName": "ElectronApp",
        "copyright": "Copyright ? 2022 <項目名稱>",
        "mac": {
            "category": "public.app-category.utilities"
        },
        "nsis": {
            "oneClick": false,
            "allowToChangeInstallationDirectory": true
        },
        "files": [
            "dist/**/*",
            "electron/**/*"
        ],
        "directories": {
            "buildResources": "assets",
            "output": "dist_electron"
        }
    }

注意electron/main.js里的配置


image.png

執(zhí)行打包命令
npm run electron:build
出現(xiàn)報錯Error: Cannot find module ‘fs/promises’

image.png

搜索了下是node版本太低

成功后當前項目下出現(xiàn)dist_electron文件夾,即為桌面應用安裝包。

提示:多次打包如果報錯,可刪除dist_electron文件夾,再進行打包。
引用地址

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

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

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