本文采用vite + vue2 + javascript + electron开发桌面软件。
为什么采用vite+electron构建桌面环境,因为vite快速,且能解决webpack + vue + electron-builder运行,windows内存爆满问题。
创建vite + vue2项目
1、先创建一个vite项目
将ts后缀偶读改成js且将vue3的代码改成vue2格式
2、兼容vue2
安装vue2的版本
命令行:npm install vite-plugin-vue2 vue-template-compiler -D,在vite.config.js中修改
/*
* @Descripttion:
* @version:
* @Author: AowCt <awoct10@163.com>
* @Date: 2023-03-03 17:52:09
* @LastEditors: AowCt <awoct10@163.com>
* @LastEditTime: 2023-03-06 10:52:49
*/
// 注意,vite目前不支持 require 引入,必须全部使用 import
import {
defineConfig } from 'vite'
import {
createVuePlugin } from 'vite-plugin-vue2'
export default defineConfig(({
command }) => {
return {
plugins: [createVuePlugin()]
}
})
3、修改main.js文件
import Vue from 'vue'
import './style.css'
import App from './App.vue'
new Vue({
render: h => h(App)
}).$mount('#app')
4、运行得到效果
引入electron
1、安装electron
npm install electron electron-builder vite-plugin-electron vite-plugin-electron-renderer -D
2、创建electron文件夹
// main/index.js
/*
* @Descripttion:
* @version:
* @Author: AowCt <awoct10@163.com>
* @Date: 2023-03-06 10:38:56
* @LastEditors: AowCt <awoct10@163.com>
* @LastEditTime: 2023-03-06 11:51:17
*/
'use strict'
import {
app, protocol, BrowserWindow } from 'electron'
const isDevelopment = process.env.NODE_ENV !== 'production'
import * as path from 'path'
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{
scheme: 'app', privileges: {
secure: true, standard: true } }
])
process.env.DIST_ELECTRON = path.join(__dirname, '..')
process.env.DIST = path.join(process.env.DIST_ELECTRON, '../dist')
process.env.PUBLIC = process.env.VITE_DEV_SERVER_URL
? path.join(process.env.DIST_ELECTRON, '../public')
: process.env.DIST
async function createWindow () {
const preload = path.join(__dirname, '../preload/index.js')
const url = process.env.VITE_DEV_SERVER_URL
const indexHtml = path.join(process.env.DIST, 'index.html')
// Create the browser window.
const win = new BrowserWindow({
width: 800