博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
helloworld of vue + electron 开发过程日志
阅读量:4538 次
发布时间:2019-06-08

本文共 10044 字,大约阅读时间需要 33 分钟。

helloworld 开发过程日志

helloworld of vue + electron

1. 相关技术栈

  • 是由Google主导开发的网页浏览器
  • 是一个基于 Chrome V8 引擎的 JavaScript 运行环境
  • 是由Github开发,用HTML,CSS和JavaScript来构建跨平台桌面应用程序的一个开源库。
    Electron通过将Chromium和Node.js合并到同一个运行时环境中,并将其打包为系统应用。
    Electron = Chromium + Node.js 看作成一个被 JavaScript 控制的,精简版的 Chromium 浏览器
    从开发的角度来看, Electron application 本质上是一个 Node.js 应用程序
  • Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式前端框架
  • 是一个基于 Vue.js 进行快速开发的完整系统

使用vue.js做前端 + Electron做后端开发应用,不仅能像web开发那样方便开发UI,又能通过Electron使用原生模块调用和扩展功能

2. 安装开发环境

当前使用的操作系统为Window10

2.1. 安装Node.js

从下载Node.js, 安装完后在命令行下输入node 就可以执行js脚本了

G:\Working> node> console.log('hello world')hello worldundefined

当前使用版本:

G:\Working> node -vv10.9.0

2.2. 使用NPM(节点包管理器)镜像

国内使用npm速度有点慢,所以建议安装CNPM

npm install cnpm

2.3. 安装vue-cli

使用来快速搭建vue项目主要是vue生态的标准化,项目的目录结构,入口文件都是大家熟悉的

cnpm install -g @vue/cli

当前使用的版本:

G:\Working> vue -V3.10.0

3. hello world

3.1. 创建项目

  • 创建名为helloword的vue项目,
vue create helloworld
  • 为了helloword最简单我选择手动选择模块
Vue CLI v3.10.0? Please pick a preset:  default (babel, eslint)> Manually select features
  • 什么模块都不选
Vue CLI v3.10.0? Please pick a preset: Manually select features? Check the features needed for your project: ( ) Babel ( ) TypeScript ( ) Progressive Web App (PWA) Support ( ) Router ( ) Vuex ( ) CSS Pre-processors>( ) Linter / Formatter ( ) Unit Testing ( ) E2E Testing
  • Babel, PostCSS, ESLint使用单独的配置文件
Vue CLI v3.10.0? Please pick a preset: Manually select features? Check the features needed for your project:? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys)> In dedicated config files  In package.json
  • 当前配置不应用到以后的项目
Vue CLI v3.10.0? Please pick a preset: Manually select features? Check the features needed for your project:? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files? Save this as a preset for future projects? (y/N) n
  • 完成
Vue CLI v3.10.0✨  Creating project in G:\Working\helloworld.?  Initializing git repository...⚙  Installing CLI plugins. This might take a while...added 958 packages from 879 contributors and audited 12068 packages in 115.58sfound 0 vulnerabilities?  Invoking generators...?  Installing additional dependencies...added 3 packages from 1 contributor and audited 12072 packages in 18.392sfound 0 vulnerabilities⚓  Running completion hooks...?  Generating README.md...?  Successfully created project helloworld.?  Get started with the following commands: $ cd helloworld $ npm run serve
  • 目录结构:
src│  App.vue│  main.js│├─assets│      logo.png│└─components        HelloWorld.vue

3.2. 运行VUE项目

执行 npm run serve 启动项目

G:\Working> cd helloworldG:\Working\helloworld> npm run serve> helloworld@0.1.0 serve G:\Working\helloworld> vue-cli-service serve INFO  Starting development server... 98% after emitting CopyPlugin DONE  Compiled successfully in 3806ms                                                                                                                        00:11:43  App running at:  - Local:   http://localhost:8080/  - Network: http://192.168.3.6:8080/  Note that the development build is not optimized.  To create a production build, run npm run build.

此时,我们可以使用浏览器通过上而两个URL来访问我们的Vue项目了

提示使用npm run build来创建生产版本

npm run build

生成了一个dist目录,里面就是打包好的发行版本了,我们用浏览器打开里面index.html文件

什么?一片空白
看看打包后的源码,原来打包后的路径开头都是 /也就是根目录,而我们需要的是相对路径
helloworld目录下添加vue.config.js文件, 并加入配置

module.exports = {  publicPath: process.env.NODE_ENV === 'production'    ? './'    : './'}

然后OK了,浏览器访问没问题了,但多了个配置文件,看看能不能在代码里解决这问题呢

3.3. 安装electron

我们的目的是要在electron上跑VUE,所以还得安装electron.

cnpm install --save-dev electron

3.4. 通过electron运行VUE项目

安装完了,可怎么能在electron 上运行vue呢?

  • 第一种方式
    • 先运行vue项目 cnpm run serve
    • 然后再通过electron访问
    node_modules\.bin\electron http://localhost:8080/
  • 第二种方式
    • 先用命令npm run build打包vue项目
    • 然后通过electron加载打包好的项目就行了
    cnpm run build && electron dist/index.html

    但这样在build时,mode 默认为production不适合调试,因为源码都会被压缩了,调试要改成development好些

    vue-cli-service build --mode development && electron dist/index.html

我们是通过electron可以使用我们的VUE项目了,但我们仅仅把electron当做最简单的浏览器在使用, 我们并没有使用electron的功能,如菜单,窗口等.

查看electron的文档, 提示复制并运行这个库

看看里面的main.js里怎么加载web应用的

// and load the index.html of the app.  mainWindow.loadFile('index.html')

这样不就可以加截我们vue项目打包后的index.html文件了吗

index.js:

const { app, BrowserWindow } = require('electron')let mainWindowfunction createWindow () {  // 创建浏览器窗口。  mainWindow = new BrowserWindow({    width: 1024,    height: 768,    webPreferences: {      nodeIntegration: true    }  })  mainWindow.loadURL(`file://${__dirname}/index.html`)  // 打开开发者工具  if (process.env.NODE_ENV === 'development') {    mainWindow.webContents.openDevTools()  }  mainWindow.on('closed', () => {    mainWindow = null  })}app.on('ready', createWindow)// 当全部窗口关闭时退出。app.on('window-all-closed', () => {  if (process.platform !== 'darwin') {    app.quit()  }})app.on('activate', () => {  if (mainWindow === null) {    createWindow()  }})

参考 electron-quick-start的main.js的,我们需要实现一个electron的入口文件,但这文件放哪呢?

主进程和渲染器进程

Electron 运行 package.json 的 main 脚本的进程被称为主进程。 在主进程中运行的脚本通过创建web页面来展示用户界面。 一个 Electron 应用总是有且只有一个主进程。

由于 Electron 使用了 Chromium 来展示 web 页面,所以 Chromium 的多进程架构也被使用到。 每个 Electron 中的 web 页面运行在它自己的渲染进程中。
修改package.json, 增加mian脚本

"main":"dist/index.js",

把electron的入口文件Index.js从src复制到dist目录下

linux & powershell:cp .\src\index.js .\dist\cmd:copy .\src\index.js .\dist\

打包vue项目

npm run build

并运行electron入口文件index.js

electron .

为了以后源码的目录更清晰,重新组织一下源码结构,根据electron的进程来组织, vue项目作为渲染进程, electron入口相关的就是主进程了

当前目录结构:

src│  App.vue│  main.js│  index.js├─assets│      logo.png│└─components        HelloWorld.vue

重新组织后

src├─electron│      index.js│└─renderer    │  App.vue    │  main.js    │    ├─assets    │      logo.png    │    └─components            HelloWorld.vue

但这时我们运行npm run servenpm run build时就会出错了,因为vue-cli找不到入口文件了,需要重新指定入口文件, 修改package.json

"scripts": {-    "serve": "vue-cli-service serve",-    "build": "vue-cli-service build"+    "serve": "vue-cli-service serve src/renderer/main.js",+    "build": "vue-cli-service build src/renderer/main.js"   },

此时还有个问题,我们执行的electron入口文件index.js还是在src\electron目录下的,

我们在执行npm run build build Vue项目时,index.js并没有被打包到dist目录下,
这样不利于生产版本的发行等

两种把electron.js打包并放到dist目录的方式:

  1. 根据开发环境写个脚copy到dist下,但这样代码就没有被打包过,适合调试
  2. 同vue-cli一样使用webpack, webpack-cli

我选择第2种使用webpack,试运行下webpack命令, node_modules\.bin\webpack 提示是否安装webpack-cli, no,我们手动安装下

安装webpack-cli

cnpm install --save-dev webpack-cli

还是去看

官方提到这个例子,参考下
https://github.com/electron-react-boilerplate/electron-react-boilerplate
添加一个electron入口文件的webpack配置文件webpack.electron.config.js

'use strict'const path = require('path')module.exports = {  entry: {    main: path.join(__dirname, 'src/electron/index.js')  },  output: {    filename: 'index.js',    path: path.join(__dirname, './dist')  },  target: 'electron-main'}

打包vue项目

npm run build

打包electron入口文件index.js

.\node_modules\.bin\webpack-cli --config .\webpack.electron.config.js

运行electron

electron .

空白?查看控制台信息,提示

Not allowed to load local resource: file://index.html

原来webpack打包electron后,路径不对了

参考
默认为:

__filename: 'mock',    __dirname: 'mock',

更改webpack.electron.config.js,打包后不使用真实路径

node: {    __dirname: false,    __filename: false  },

重新打包运行electron

.\node_modules\.bin\webpack-cli --config .\webpack.electron.config.jselectron .

成功运行

3.5. 使用electron-builder 打包发布

看到不少项目使用,就用这个吧

  • 安装electron-builder
cnpm install --save-dev electron-builder

参考文档修改package.json, 添加build字段:

"build": {    "productName": "helloworld",    "appId": "nononoone.helloworld",    "npmRebuild": false,    "electronDownload": {      "mirror": "https://npm.taobao.org/mirrors/electron/",      "isVerifyChecksum": false    },    "directories": {      "output": "build"    },    "files": [      "dist/**/*"    ],    "dmg": {      "contents": [        {          "x": 410,          "y": 150,          "type": "link",          "path": "/Applications"        },        {          "x": 130,          "y": 150,          "type": "file"        }      ]    },    "mac": {      "icon": "build/icons/icon.icns"    },    "win": {      "icon": "build/icons/icon.ico",      "extraResources": [        "./dist/**/*.dll"      ]    },    "linux": {      "icon": "build/icons"    }  },

运行electron-builder命令:

.\node_modules\.bin\electron-builder

过程中要下载electron-builder的依赖文件真的慢死了,不过最终还是下完了

最后生成了一个build目录:

Mode                LastWriteTime         Length Name----                -------------         ------ ----d-----        2019/8/18      1:52                win-unpacked-a----        2019/8/18      1:50            549 builder-effective-config.yaml-a----        2019/8/18      1:53       43837331 helloworld Setup 0.1.0.exe-a----        2019/8/18      1:53          45860 helloworld Setup 0.1.0.exe.blockmap

win-unpacked目录相当于绿色版

helloworld Setup 0.1.0.exe就是安装包了
到此helloworld从开始到发布的基本流程就走完了

4. 完善配置

整个流程我们是走完了,但很多命令都是通过手动完成的,我们需要整理完善

修改package.json和完善脚本命令:

"scripts": {    "pack": "vue-cli-service build src/renderer/main.js && webpack-cli --config webpack.electron.config.js",    "build": "npm run pack && electron-builder",    "pack:dev": "vue-cli-service build src/renderer/main.js --mode development && webpack-cli --mode development --config webpack.electron.config.js",    "debug": "npm run pack:dev && electron .",    "serve": "npm run debug"  },

5. 总结

对比vue-cli创建的初始项目:

$ git statusOn branch masterChanges not staged for commit:  (use "git add/rm 
..." to update what will be committed) (use "git checkout --
..." to discard changes in working directory) modified: .gitignore modified: package.json deleted: src/App.vue deleted: src/assets/logo.png deleted: src/components/HelloWorld.vue deleted: src/main.jsUntracked files: (use "git add
..." to include in what will be committed) src/electron/ src/renderer/ vue.config.js webpack.electron.config.js "开发过程日志.md"no changes added to commit (use "git add" and/or "git commit -a")

到此,一个简单的vue + electron 开发模板就完成了,但这是不够的,还有很多工作要做,如

  • 使用vue-cli给vue项目增加elist,babel等插件
  • 使用原生模块,如ffi
  • 等等

所以接下来看看在helloworld的基础上如何进一步搭建我的世界

项目地址

转载于:https://www.cnblogs.com/liangtian/p/11371284.html

你可能感兴趣的文章
div+css 兼容ie6 ie7 ie8 ie9和FireFox Chrome等浏览器方法(非原创)
查看>>
关于SDWebImage加载高清图片导致app崩溃的问题
查看>>
如何查看方法在哪里被调用
查看>>
HUE的自动化安装部署
查看>>
图片服务器(FastDFS)的搭建
查看>>
myBatis应用
查看>>
RuntimeError: DataLoader worker (pid 18255) is killed by signal: Killed.
查看>>
[PHP] 用AppServ一步到位安装PHP服务器
查看>>
mac brew install redis 报错
查看>>
Work? working!
查看>>
给UINavigationBar自定义颜色
查看>>
开源收藏
查看>>
CentOS7下FTP的安装与配置
查看>>
即使是学习,也还是多出门学习比较好!
查看>>
zoj 3432 Find the Lost Sock (ZOJ Monthly, November 2010)
查看>>
linux目录结构
查看>>
数据库索引分类
查看>>
python 内置函数
查看>>
iOS真机调试遇到No such file or directory的问题
查看>>
POSTMAN-REST Client
查看>>