初始化
npm init vue cnpm install cnpm i electron electron-builder -D
|
在src
目录下新建background.ts
(electron主进程文件)
在根目录下新建文件夹plugins
,在里面新建vite.electron.dev.ts
以及vite.electron.build.ts
(避免启动两个终端分别启动vue和electron)
配置开发环境electron
编辑vite.electron.dev.ts
import type {Plugin} from "vite"; import type {AddressInfo} from "net"; import {spawn} from 'child_process'; import fs from 'node:fs'
const buildBackground=()=>{{ require('esbuild').buildSync({ entryPoints:['src/background.ts'], bundle:true, outfile:'dist/background.js', platform:'node', target:'node12', external:['electron'] }) }} export const electronDevPlugin=():Plugin=>{ return{ name:'electron-dev', configureServer(server){ buildBackground() server?.httpServer?.once('listening',()=>{ const addressInfo=server.httpServer?.address() as AddressInfo const IP=`http://localhost:${addressInfo.port}` let electronProcess = spawn(require('electron'),['dist/background.js',IP]) fs.watchFile('src/background.ts',()=>{ electronProcess.kill() buildBackground() electronProcess=spawn(require('electron'),['dist/background.js',IP]) }) electronProcess.stderr.on('data',(data)=>{ console.log(data.toString()) }) }) } } }
|
编辑tsconfig.node.json
,在include
加上:
编辑background.ts
import {app,BrowserWindow} from 'electron'
app.whenReady().then(()=>{ const win=new BrowserWindow({ width:1280, height:720, webPreferences: { nodeIntegration:true, contextIsolation:false, webSecurity:false } })
if(process.argv[2]){ win.loadURL(process.argv[2]) } else{ win.loadFile('index.html') }
})
|
编辑vite.config.ts
,导入并添加开发环境插件
import {electronDevPlugin} from "./plugins/vite.electron.dev";
|
在plugins
处加入
配置生产环境electron
编辑vite.electron.build.ts
2024/06/11更新:取消注释files:['**/*'],
import type {Plugin} from "vite"; import fs from 'node:fs' import * as electronBuilder from 'electron-builder'; import * as path from "node:path";
const buildBackground=()=>{{ require('esbuild').buildSync({ entryPoints:['src/background.ts'], bundle:true, outfile:'dist/background.js', platform:'node', target:'node12', external:['electron'] }) }}
export const electronBuildPlugin=():Plugin=>{ return{ name:'electron-build', closeBundle() { buildBackground() const packageJson=JSON.parse(fs.readFileSync('package.json','utf-8')) packageJson.main='background.js' fs.writeFileSync('dist/package.json',JSON.stringify(packageJson,null,4)) fs.mkdirSync('dist/node_modules')
electronBuilder.build({ config:{ directories:{ output:path.resolve(process.cwd(),'release'), app:path.resolve(process.cwd(),'dist'), }, files:['**/*'], asar:true, productName:'media-transformer', nsis:{ oneClick:false, allowToChangeInstallationDirectory: true, } }, }) }, } }
|
编辑vite.config.ts
,导入并添加生产环境插件
import {electronBuildPlugin} from "./plugins/vite.electron.build";
|
在plugins
处加入
参考链接
小满Vue3(第三十九章 electron桌面程序)_哔哩哔哩_bilibili
Rean's Blog
Enjoy technology and music