參考文章
手把手教你如何新建一個(gè)vue3+electron項(xiàng)目_搭建一個(gè)vue3+electron的項(xiàng)目-CSDN博客
安裝 | electron-egg (kaka996.com)
其中遇到問題,特記錄如下。
ES6模式報(bào)錯(cuò)
App threw an error during load
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'D:\vs2024proj\electron_vite_ts_demo_sunny\electron-vite-demo-sunny\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
ES6模式下不能使用require。解決辦法更改package.json,刪除?"type": "module".



屏蔽告警信息
參考?Electron Security Warning (Insecure Content-Security-Policy) 告警解決-CSDN博客
使用了方法一和方法二。
方式一:index.html文件里設(shè)置安全策略
在HTML主文件的頭部引入安全策略的設(shè)置,采用如下設(shè)置,Electron的控制臺(tái)就不會(huì)顯示告警了:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">
方式二:main.js文件里屏蔽安全告警
在Electron工程啟動(dòng)文件main.js的頭部設(shè)置以下內(nèi)容,也可以屏蔽安全告警在console控制臺(tái)的顯示:
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
至此第二步完成。
三、加入electron預(yù)加載腳本,并通過其進(jìn)行electron和vue的交互
通訊

/preload/index.js文件代碼如下:
-------------------------------
const { contextBridge, ipcRenderer } = require('electron')
const handleSend = async (vue_params) => {
? let fallback = await ipcRenderer.invoke('sent-event', vue_params)
? return fallback
}
?// 暴漏函數(shù),能暴露的不僅僅是函數(shù),我們還可以暴露變量
contextBridge.exposeInMainWorld('myApi', {
? handleSend: handleSend,
? setTitle: (title) => ipcRenderer.send('set-title', title) ,
? openFile: () => ipcRenderer.invoke('dialog:openFile')
})
-----------------------------------
主進(jìn)程main.js源碼
-------------------------
const { app, BrowserWindow,ipcMain,dialog } = require('electron')
const path = require('path');
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'; //屏蔽安全告警
const createWindow = () => {
? const win = new BrowserWindow({
? ? width: 800,
? ? height: 600,
? ? webPreferences: {
? ? ? preload: path.join(__dirname, './preload/index.js')
? ? }
? })
? // win.loadFile('index.html')
? // 下面的url為自己?jiǎn)?dòng)vite項(xiàng)目的url。
? win.loadURL('http://127.0.0.1:5173/')
? // 打開electron的開發(fā)者工具
? win.webContents.openDevTools({ mode: 'detach' })
}
ipcMain.handle('sent-event', (event,params) => {
? console.log(params)
? return '1111'
})
// 渲染進(jìn)程中更改標(biāo)題
const handleSetTitle = (event, title) => {
? const webContents = event.sender
? const win = BrowserWindow.fromWebContents(webContents)
? win.setTitle(title)
}
ipcMain.on('set-title', handleSetTitle)
//打開文件
async function handleFileOpen() {
? const { canceled, filePaths } = await dialog.showOpenDialog()
? if (canceled) {
? ? return
? } else {
? ? return filePaths[0] // 返回文件名給渲染進(jìn)程
? }
}
ipcMain.handle('dialog:openFile', handleFileOpen)
app.whenReady().then(() => {
? createWindow()
? app.on('activate', () => {
? ? if (BrowserWindow.getAllWindows().length === 0) createWindow()
? })
})
app.on('window-all-closed', () => {
? if (process.platform !== 'darwin') {
? ? app.quit()
? }
})
------------------------
vue中調(diào)用方法
----------------------------------
<template>
<div class="ipc-test-view"> ? ?
? ? <button @click="onSendTile">進(jìn)程通訊測(cè)試</button>
? ? <button @click="onOpenFile">打開文件</button> ?
? ? <div>{{fileName}}</div> ?
</div>
</template>
<script setup>
?import { ref, reactive } from 'vue'
?const fileName=ref('')
const onSendTile = ()=>{
? ? const title ='11111'
? ? window.myApi?.setTitle(title)
}
? ?async function onOpenFile () {
? ? const filePath = await window.myApi?.openFile()
? console.log(filePath);
? fileName.value = filePath;
}
</script>
<style scoped>
.ipc-test-view{
? ? border:solid 1px pink;
? ? width: 300px;
? ? height: 300px;;
}
</style>
--------------------------------------
四、優(yōu)化開發(fā)體驗(yàn)
1. 安裝nodemon依賴
2. 更改啟動(dòng)配置,在package.json中的scripts添加這句進(jìn)行啟動(dòng)electron項(xiàng)目,nodemon在檢測(cè)到有以.js,.html結(jié)尾文件發(fā)生變動(dòng)時(shí),就會(huì)重啟窗口。
"start": "nodemon --exec electron . --watch ./ --ext .js,.html"

五?vite + vue3 + Antd 搭建后臺(tái)管理系統(tǒng)
npm install ant-design-vue --save
更改 /src/main.ts
-------------------------------------
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import Antd from "ant-design-vue";
import 'ant-design-vue/dist/antd.css';
const app = createApp(App)
app.use(Antd)
app.use(createPinia())
app.use(router)
app.mount('#app')
------------------------------------------
七、自定義窗口(不使用原生的窗口)
八、項(xiàng)目打包
--------------------------------------------------
"build": {
? ? "appId": "com.zm666.desktop",//包名?
? ? "productName": "electron測(cè)試", //項(xiàng)目名 這也是生成的exe文件的前綴名
? ? "asar": true,
? ? "copyright": "Copyright ? 2023 electron",//版權(quán)? 信息
? ? "publish": {
? ? ? "provider": "generic",// 服務(wù)器提供商 也可以是GitHub等等
? ? ? "url": ""http:// 服務(wù)器地址
? ? },
? ? "directories": { // 輸出文件夾
? ? ? "output": "electron-build/"
? ? },
? ? "extraResources": [
? ? ? {
? ? ? ? "from": "./public",
? ? ? ? "to": "./public"
? ? ? }
? ? ],
? ? "files": [ // 打包的electron需要包含的文件,一般就是與electron的有關(guān)的打包進(jìn)去
? ? ? "main.js", // electron主入口文件
? ? ? "controller", // 也是主入口文件,只不過拆成了兩個(gè)文件
? ? ? "preload" //預(yù)加載文件
? ? ],
? ? "mac": {
? ? ? "artifactName": "${productName}_${version}.${ext}",
? ? ? "target": [
? ? ? ? "dmg"
? ? ? ]
? ? },
? ? "win": {
? ? ? "icon": "public/logoTemplate.ico",
? ? ? "target": [
? ? ? ? {
? ? ? ? ? "target": "nsis",
? ? ? ? ? "arch": [
? ? ? ? ? ? "ia32"
? ? ? ? ? ]
? ? ? ? }
? ? ? ],
? ? ? "artifactName": "${productName}_${version}.${ext}"
? ? },
? ? "nsis": {
? ? ? "oneClick": false,// 是否一鍵安裝
? ? ? "perMachine": false,
? ? ? "allowToChangeInstallationDirectory": true,// 允許修改安裝目錄
? ? ? "deleteAppDataOnUninstall": false,
? ? ? "installerIcon": "public/favicon.ico",// 安裝圖標(biāo)
? ? ? "uninstallerIcon": "public/favicon.ico",// 創(chuàng)建桌面圖標(biāo)
? ? ? "createDesktopShortcut": true,// 創(chuàng)建桌面圖標(biāo)
? ? ? "createStartMenuShortcut": true,// 創(chuàng)建開始菜單圖標(biāo)
? ? ? "shortcutName": "zm666測(cè)試平臺(tái)" // 圖標(biāo)名稱
? ? },
? ? "releaseInfo": {
? ? ? "releaseNotes": "版本更新的具體內(nèi)容"
? ? }
? }
------------------------------------------------------
? downloading url=https://registry.npmmirror.com/-/binary/electron/28.2.0/electron-v28.2.0-win32-ia32.zip
size=94 MB parts=8
? ? downloaded? ? ? url=https://registry.npmmirror.com/-/binary/electron/28.2.0/electron-v28.2.0-win32-ia32.zip
duration=2.113s
第一次下載包報(bào)錯(cuò)了。
然后我使用這個(gè)網(wǎng)絡(luò)連接https://registry.npmmirror.com/-/binary/electron/28.2.0/electron-v28.2.0-win32-ia32.zip下載了這個(gè)包,但是不知道往哪里放。
最后想到一個(gè)方法,打開優(yōu)途加速器,連接快速通道,包就下載成功了。

打包成功了。
