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. 當準備將應(yīng)用發(fā)布到生產(chǎn)環(huán)境時,運行:
> npm run build

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

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

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啟動服務(wù)艇炎,然后electron去加載本地服務(wù)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向楼、打包生成桌面應(yīng)用

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文件夾谐区,即為桌面應(yīng)用安裝包湖蜕。

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市炼杖,隨后出現(xiàn)的幾起案子灭返,更是在濱河造成了極大的恐慌,老刑警劉巖坤邪,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件婆殿,死亡現(xiàn)場離奇詭異,居然都是意外死亡罩扇,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門怕磨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來喂饥,“玉大人,你說我怎么就攤上這事肠鲫≡卑铮” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵导饲,是天一觀的道長捞高。 經(jīng)常有香客問我,道長渣锦,這世上最難降的妖魔是什么硝岗? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮袋毙,結(jié)果婚禮上型檀,老公的妹妹穿的比我還像新娘。我一直安慰自己听盖,他們只是感情好胀溺,可當我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布裂七。 她就那樣靜靜地躺著,像睡著了一般仓坞。 火紅的嫁衣襯著肌膚如雪背零。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天无埃,我揣著相機與錄音徙瓶,去河邊找鬼。 笑死录语,一個胖子當著我的面吹牛倍啥,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播澎埠,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼虽缕,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蒲稳?” 一聲冷哼從身側(cè)響起氮趋,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎江耀,沒想到半個月后剩胁,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡祥国,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年昵观,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片舌稀。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡啊犬,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出壁查,到底是詐尸還是另有隱情觉至,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布睡腿,位于F島的核電站语御,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏席怪。R本人自食惡果不足惜应闯,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望何恶。 院中可真熱鬧孽锥,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至盛撑,卻和暖如春碎节,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背抵卫。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工狮荔, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人介粘。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓殖氏,卻偏偏與公主長得像,于是被迫代替她去往敵國和親姻采。 傳聞我的和親對象是個殘疾皇子雅采,可洞房花燭夜當晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容