vue项目使用Electron开发桌面应用
添加npm配置避免安装Electron错误
请确保您的 node 版本大于等于 18.
cmd运行: npm config edit
该命令会打开npm的配置文件,请在空白处添加:
electron_builder_binaries_mirror=https://npmmirror.com/mirrors/electron-builder-binaries/
electron_mirror=https://cdn.npmmirror.com/binaries/electron/
registry=https://registry.npmmirror.com/
然后保存并关闭该窗口
因为一些众所周知的原因,建议国内的小伙伴使用cnpm安装并且把源改为淘宝镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
开始全局安装 Electron
cnpm install electron -g
安装完成运行electron -V,查看是否安装成功
在vue项目中安装
vue add electron-builder
安装过程报错的话一般是 vue-cli-plugin-electron-builder 安装失败,重新安装一下即可:
cnpm i vue-cli-plugin-electron-builder -D
安装完成后 package.js 中会增加两个脚本(运行/打包):
“electron:build”: “vue-cli-service electron:build”
“electron:serve”: “vue-cli-service electron:serve”
Electron消顶部默认菜单栏
在background.js中配置 Menu.setApplicationMenu(null) :
import { Menu } from 'electron'async function createWindow() {Menu.setApplicationMenu(null) // null值取消顶部菜单栏// Create the browser window.const win = new BrowserWindow({width: 800,height: 600,webPreferences: {// Required for Spectron testingenableRemoteModule: !!process.env.IS_TEST,// Use pluginOptions.nodeIntegration, leave this alone// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more infonodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION}})if (process.env.WEBPACK_DEV_SERVER_URL) {// Load the url of the dev server if in development modeawait win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)if (!process.env.IS_TEST) win.webContents.openDevTools()} else {createProtocol('app')// Load the index.html when not in developmentwin.loadURL('app://./index.html')}
}