electron-vue 应用的构建

  可能会有人认为这个架构构建起来非常简单,不需要指南就可以。甚至从空白到运行软件就三局句命令行的事情(官方就是这么认为的)如图:


但是下面是我在我的电脑上的实际情况,大家可以进行参考。

首先要说明的就是我的安装环境(我偏向于在开发过程中使用yarn而不是npm):
yarn的安装命令行(已经安装nodejs的情况下,未安装的链接如下都是官方链接):

Windows 安装包

macOS安装包

源代码

1
2
3
4
5
6
npm i yarn -g

NodeJS Version: 12.16.1 LTS
npm Version: 6.13.4
Vue Version: 2.9.6
yarn Version: 1.22.4

我们接下来要安装全局的脚手架:
1
npm install -g vue-cli

第一步一定是在预定的文件夹中创建一个新的electron-vue项目:
1
vue init simulatedgreg/electron-vue (project-name here)

第二步下载依赖:
1
yarn

第三步本地启动调试版本:
1
yarn run dev

理论上到这里已经结束了,我们应该看到的应用界面是这样的:

但是呢我一开始并不是这样的界面,专门去GitHub上找了issue,发现是因为NodeJS版本太新导致的,下面是解决方法:

我一开始看到的界面报错是这样的:

1
2
3
4
5
6
7
8
9
10
ReferenceError: process is not defined

- index.ejs:11 eval
[.]/[html-webpack-plugin]/lib/loader.js!./src/index.ejs:11:2

- index.ejs:16 module.exports
[.]/[html-webpack-plugin]/lib/loader.js!./src/index.ejs:16:3

- index.js:284
/[html-webpack-plugin]/index.js:284:18 - runMicrotasks - task_queues.js:97 processTicksAndRejections internal/process/task_queues.js:97:5

解决方法其实是蛮简单的就是将项目的根目录下的.electron-vue目录中的webpack.renderer.config.js中的HtmlWebpackPlugin的定义修改为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, '../src/index.ejs'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
},
templateParameters(compilation, assets, options) {
return {
compilation: compilation,
webpack: compilation.getStats().toJson(),
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options: options
},
process,
};
},
nodeModules: process.env.NODE_ENV !== 'production'
? path.resolve(__dirname, '../node_modules')
: false
}),

再将webpack.web.config.js中的 HtmlWebpackPlugin 的定义修改为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, '../src/index.ejs'),
templateParameters(compilation, assets, options) {
return {
compilation: compilation,
webpack: compilation.getStats().toJson(),
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options: options
},
process,
};
},
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
},
nodeModules: false
}),
new webpack.DefinePlugin({
'process.env.IS_WEB': 'true'
}),

这样就可以基本上完美的解决问题。

加一笔

这里再多加一笔,在新版本的electron中可能会出现用require引用的时候报错:

1
require not defined

这个问题的来源是官方修改了nodeIntergration中的默认值,官方描述如下:
The default values of nodeIntegration and webviewTag are now false to improve security.
所以在新建任何一个需要require的页面时需要添加如下代码:
1
2
3
webPreferences: {
nodeIntegration: true
}

至此现阶段碰到的问题我已经基本解决,关于Electron-Vue的应用开发的技术笔记会持续进行更新。