搭建Electron+Vue3开发环境

3,262 阅读3分钟

原文链接: 搭建Electron+Vue3开发环境 - 愧怍的小站

之前用electron-vue写过一个半成品的桌面端应用,但是是基于Vue2的,最近又想重写点桌面端应用,想要上Vue3+TypeScript,于是便有了这篇文章总结下具体的搭建过程。

Vue Cli

Vue CLI 有一个插件vue-cli-plugin-electron-builder,可以非常方便的搭建electron环境。

npm i @vue/cli -g
vue create my-app

根据自己项目的需求选择对应的依赖(例如Babel,TS,Vuex等等)

Vue CLI v5.0.3
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, TS, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? Yes
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass)
? Pick a linter / formatter config: Prettier
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
? Save this as a preset for future projects? No


Vue CLI v5.0.3
✨  Creating project in F:\Electron\my-app.
🗃  Initializing git repository...
⚙️  Installing CLI plugins. This might take a while...

安装vue-cli-plugin-electron-builder

Vue CLI Plugin Electron Builder (nklayman.github.io)

cd my-app
vue add electron-builder

安装过程中会提示你选择Electron的版本,选择最新版本即可

启动项目

npm run electron:serve

参考文章:Electron + Vue3 开发跨平台桌面应用【从项目搭建到打包完整过程】 - 掘金 (juejin.cn)

error  in ./src/background.ts

Module build failed (from ./node_modules/ts-loader/index.js):
TypeError: loaderContext.getOptions is not a function

我测试的时候,@vue/cli-plugin-typescript版本为~5.0.0,就会导致编译类型出错,将package.json中改为"@vue/cli-plugin-typescript": "~4.5.15",即可正常运行(但还是会有DeprecationWarning)

Vite

上面是使用Vue Cli脚手架进行开发,如果想上Vite的话,就需要用Vite来构建项目,然后安装electron的相关依赖。

这个不是作为重点,因为很多大佬都已经写了现成的模板,完全可以自行借鉴学习,就贴几个阅读过的几篇文章

Vite + Vue 3 + electron + TypeScript - DEV Community

2021年最前卫的跨平台开发选择!vue3 + vite + electron - 知乎 (zhihu.com)

现成的模板

均可在github上搜索到

electron-vite脚手架(推荐)

当然也可以使用脚手架,可选择React与Vue,实际上也就是创建上面的前两个模板

npm create electron-vite

总结

因为Electron本质上还是一个浏览器,无论是Vue还是React开发也好,在传统网页开发的时候都有对应的调试地址,如http://127.0.0.1:3000,而electron的做法无非就是开启一个浏览器,然后和正常的网页开发一样,并提供桌面端的api使用。

目前社区两大Vue+Electron的脚手架主要是electron-vuevue-cli-plugin-electron-builder,更多electron的开源项目都遵循着前者的项目结构,像上面的模板也就是。

以上就是我所使用Vue3来开发Electron的环境搭建过程,总体来说从Electron除了应用体积过大,对于前端开发者来说是非常友好的,既然环境配置完,那么现在就可以开始好好的编写桌面端应用了。