整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

Electron 13结合Vuejs3创建桌面应用程序-环境搭建篇

Electron + vue3

1.Electronjs

electron概念:

Electron 是一个基于Chromium 和 Node.js实现的桌面应用框架,可以使用 JavaScript, HTML 和 CSS 等 Web 技术构建原生程序,例如vscode、skype、whatsapp等都是基于electronjs框架开发的。

electron优点:

  • 跨平台,开源免费,社区活跃,一次编写,Windows、Mac、Linux都能运行。
  • 熟练前端三剑客html、css、js即可构建应用。
  • 可通过node.js、原生native api 增强web功能体验。
  • 内置chromium浏览器,兼容性好,支持html5 css3 es6+语法

2.Vuejs

vue概念:

Vue.js是一套构建用户界面的渐进式JavaScript框架,是目前流行前端三大框架之一。

vue优点:

  • 组件化开发,使冗余代码编写量大大减少,易维护。
  • 数据双向绑定,响应式开发,配合vuejs devtools浏览器插件开发效率高。
  • 虚拟dom,数据和结构的分离,结构清晰。
  • 单页面应用,页面局部刷新,运行速度更快。

环境搭建

1.nodejs准备工作

安装nodejs LTS(长期支持版本),安装完终端查看版本。

J:\test\electronjs>node -v
v14.16.0
J:\test\electronjs>npm -v
7.19.1

2.安装cnpm 或者 yarn

推荐使用全局安装cnpm,并配置淘宝源

npm install cnpm -g
cnpm config set registry https://registry.npm.taobao.org

安装完查看源设置是否成功

J:\test\electronjs>cnpm config get registry
https://registry.npm.taobao.org/

3.安装vue-cli4环境

cnpm install @vue/cli -g

安装完查看vue-cli版本

J:\test\electronjs>vue -V
@vue/cli 4.5.13

4.创建vue3项目

J:\test\electronjs>vue create vueproj1

# 点最后一项 手动选择安装
? Please pick a preset:
  Default ([Vue 2] babel, eslint)
  Default (Vue 3) ([Vue 3] babel, eslint)
> Manually select features

# 选择项目要使用的特性模块,空格勾选模块,选择完成 回车确认下一步
? Check the features needed for your project:
 (*) Choose Vue version
 (*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
>(*) Router
 (*) Vuex
 (*) CSS Pre-processors
 (*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing

# 选择3.x版本,回车下一步
? Choose a version of Vue.js that you want to start the project with
  2.x
> 3.x

# 这里选择路由是否使用历史模式,这里选择n,需要使用hash模式
? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) n

# 这里选择 默认第一项css预处理器
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
> Sass/SCSS (with dart-sass)
  Sass/SCSS (with node-sass)
  Less
  Stylus

# 选择第一项默认 错误代码检查即可
? Pick a linter / formatter config: (Use arrow keys)
> ESLint with error prevention only
  ESLint + Airbnb config
  ESLint + Standard config
  ESLint + Prettier
  
# 选择第一项即可 保存语法检查
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Lint on save
 ( ) Lint and fix on commit

# 选择第一项即可,放在专用的配置文件中
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config files
  In package.json

# 是否保存到预设给将来项目,y的话会存到.vuerc中,这里选N,等待完成创建
? Save this as a preset for future projects? (y/N) N

5.基于vue3项目搭建electron环境

# 进到刚才创建的项目目录中
J:\test\electronjs>cd vueproj1

# 使用electron-builder构建 基于vue3的electron环境
J:\test\electronjs\vueproj1>vue add electron-builder

# 目前支持到13版本,我们选择13
? Choose Electron Version (Use arrow keys)
  ^11.0.0
  ^12.0.0
> ^13.0.0

# 安装完 我们检查 electron 版本
J:\test\electronjs\vueproj1>npx electron -v
v13.3.0

6.启动开发服务

# 开发模式,实时预览
npm run electron:serve

# 编译打包
npm run electron:build

效果图如下:

项目优化:

开发环境 启动优化:

# 首次 运行服务后,默认是有请求安装 vue devtools插件
INFO  Launching Electron...
> Failed to fetch extension, trying 4 more times
Failed to fetch extension, trying 3 more times
Failed to fetch extension, trying 2 more times
Failed to fetch extension, trying 1 more times
Failed to fetch extension, trying 0 more times
Vue Devtools failed to install: Error: net::ERR_CONNECTION_TIMED_OUT

解决思路:

1.搭建vpn可以访问国外网络。

2.修改background.js主进程代码,注释掉 devtools相关代码

// 1.开发工具引入 这块注释
// import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
...
// 2.应用准备好 开发环境 尝试安装扩展 这块注释
app.on('ready', async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS3_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow()
})

electron配置预加载preload.js

electron 窗口创建时支持预加载脚本,预加载preload.js脚本处于渲染进程中,支持nodejs 语法

1.在src目录下 创建 preload.js,添加如下代码:

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.

const {contextBridge, nativeImage, ipcRenderer} = require('electron');

contextBridge.exposeInMainWorld(
    'electron',
    {
        nativeImage,
        ipcRenderer,
    }
)

2.在electron主进程 background.js 中配置上步创建的预加载js

// 引入node path模块
const path = require('path')
...

const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        ...
        // 窗口创建web首选项 新增如下配置
        
        // electron:nativeWindowOpen的默认值已被弃用,并将在electron 15中从false更改为true。
        nativeWindowOpen: true,
        
        // 开启远程模块
        enableRemoteModule: true,
        
        // 预加载配置,这里用到上面的path模块
        preload: path.join(__dirname, 'preload.js'),
    }
})

3.在项目根目录,创建 vue.config.js 并增加如下代码:

module.exports = {
    pluginOptions: {
        electronBuilder: {
            preload: 'src/preload.js',
        }
    }
}

electron远程模块remote优化

remote模块在 Electron 12 中被弃用,并将在 Electron 14 中移除。它被@electron/remote模块取代 。

1.安装扩展。

cnpm install --save @electron/remote

2.安装完成 先在主进程 src/background.js 中 增加如下

// in the main process:
require('@electron/remote/main').initialize()
...

3.扩展进程预加载 preload.js 添加如下代码:

将常用的remote模块,通过上下文桥梁(contextBridge)暴露给渲染器,页面可以使用window.electron.remote调用

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.

const {contextBridge, nativeImage, ipcRenderer} = require('electron');
const remote = require('@electron/remote');

contextBridge.exposeInMainWorld(
    'electron',
    {
        nativeImage,
        ipcRenderer,
        remote
    }
)

演示示例(调起对话框)

修改默认视图页面组件 src/views/Home.vue

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <br />
    <button @click="myDialog">点击打开系统对话框</button>
<!--    <HelloWorld msg="Welcome to Your Vue.js App"/>-->
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    // HelloWorld
  },
  methods: {
    myDialog(){
      // 通过preload.js 上下文暴露的remote对象
      window.electron.remote.dialog.showMessageBox({
        title: '系统对话框',
        type: 'info',
        message: '测试下系统对话框'
      })
    }
  }
}
</script>

效果如下:

以上就是Electron13 + Vue3 搭建环境篇内容,后续推出更多的相关文章,大家敬请期待~

.背景:
即时通讯、桌面端app开发、当用户和用户聊天,当发送聊天消息时,须要作收到消息通知,因为用到的技术栈是electron、它也有自己的通知模块、因为其他的原因暂时用不了 最后查到HTML5新增的 Notification API的通知功能。即便将浏览器窗口最小化,依然会收到消息通知、所以就先用它吧、后面再后话处理一下。

2.通知权限:
2.1 首先须要 看浏览器是否支持 Notification ,支持才有下文,不然就此止步;
2.2 经过 Notification.permission 检测用户是否容许通知:

// Notification.permission === 'granted' 用户容许
// Notification.permission === 'denied' 用户拒绝
// Notification.permission === 'denied' 不知道用户的选择,默认

if(Notification.permission === 'granted'){
    console.log('用户容许通知');
    instance_init(title, options);
}else if(Notification.permission === 'denied'){
    console.log('用户拒绝通知');
}else{
    console.log('用户还没选择,去向用户申请权限吧');
    Notification.requestPermission(function(status) {
    	if(status=='granted'){
    		console.log('用户容许通知');
    		instance_init(title, options);
    	}else if(status=='denied'){
    		console.log('用户拒绝通知');
    	}else{
    		console.log('用户还没选择');
    	}
    });
}

3. 主要用到的参数。其他参数了解:notification - Web API 接口参考 | MDNMDN Web DocsMDN logoMozilla logo

title:通知的标题
options:通知的设置选项(可选)。
	body:通知的内容。
	tag:表明通知的一个识别标签,相同tag时只会打开同一个通知窗口。
	icon:要在通知中显示的图标的URL。
	image:要在通知中显示的图像的URL。
	data:想要和通知关联的任务类型的数据。
	requireInteraction:通知保持有效不自动关闭,默认为false。

4.代码实现

4.1原生html5方式

<html>

	<head>
		<meta charset="UTF-8">
		<title>H5通知功能 </title>
	</head>

	<body>
		<script type="text/javascript">
			// 调用通知方法
			showMsgNotification('状态更新提醒','你的朋友圈有3条新状态,快去查看吧');
			/**
			 * H5通知功能 
			 */
			function showMsgNotification(out_title, out_msg) {
				var title = out_title ? out_title : '更新状态标题';
				var options = {
					body: out_msg ? out_msg : "更新状态内容", // 通知主体
					requireInteraction: true, // 不自动关闭通知
					icon: 'http://img18.house365.com/newcms/2017/03/16/148964317858ca26aacf7b5.jpg', // 通知图标 
					tag: 'hangge',
				};
				var Notification = window.Notification || window.mozNotification || window.webkitNotification; // 浏览器作兼容处理
				if(Notification) { //支持桌面通知
					if(Notification.permission == "granted") { //已经容许通知
						instance_init(title, options);
					} else {
						//第一次询问或已经禁止通知(若是用户以前已经禁止显示通知,那么浏览器不会再次询问用户的意见,Notification.requestPermission()方法无效)
						Notification.requestPermission(function(status) {
							if(status === "granted") { //用户容许
								instance_init(title, options);
							} else { //用户禁止
								console.log('禁止')
								return false
							}
						});
					}
					/**
					 * Notification定义
					 * */
					function instance_init(title, options){
						var instance = new Notification(title, options);
						instance.onclick = function() {
							console.log('onclick');
							// 关闭通知
							instance.close();
						};
						instance.onerror = function() {
							console.log('onerror');
						};
						instance.onshow = function() {
							console.log('onshow');
						};
						instance.onclose = function() {
							console.log('onclose');
						};
					}
				} else { //不支持(IE等)
					console.log("不支持的浏览器")
				}
			}
		</script>
	</body>

</html>

4.2 electron方式、调用即可

周GitHub排行精选

edex-ui

eDEX-UI 是一个全屏桌面应用程序,类似于科幻电脑界面,其灵感来自于DEX-UI和TRON Legacy电影特效。

本周 star 3082

开源项目地址:https://github.com/GitSquared/edex-ui

Big List of Naughty Strings

Big List of Naughty Strings (淘气字符串大列表)是一个持续更新的字符串列表,包括了那些在输入区域很可能就引发问题的字符串,由 Max Woolf 发起和维护。这个列表可用于自动或手工 QA 测试。

本周 star 2690

开源项目地址:https://github.com/minimaxir/big-list-of-naughty-strings

nginxconfig.io

一个在线nginx配置生成器。

本周 star 2497

开源项目地址:https://github.com/valentinxxx/nginxconfig.io

Doodle Master

涂鸦大师试图将你的UI模型转换成真实的代码。目前,这个存储库只是为了证明人工智能设计工具的概念。

本周 star 2116

开源项目地址:https://github.com/karanchahal/DoodleMaster

Lorca

一个非常小的库,用于在 Go 中构建 HTML5 桌面应用程序。它使用Chrome浏览器作为UI层。与电子产品不同的是,它没有将 Chrome 捆绑到应用程序包中,而是重用已经安装的应用程序。

本周 star 1445

开源项目地址:https://github.com/zserge/lorca

Wayne

Wayne 是一个通用的、基于 Web 的 Kubernetes 多集群管理平台。通过可视化 Kubernetes 对象模板编辑的方式,降低业务接入成本, 拥有完整的权限管理系统,适应多租户场景,是一款适合企业级集群使用的发布平台。

本周 star 1324

开源项目地址:https://github.com/Qihoo360/wayne

关注 wx - 公 - 号 -:非著名程序员,对话框回复关键字 “1024”,免费领取 30 本经典编程书籍。