Electron is an excellent framework for cross-platform desktop applications, the official website gives Jane Shao is simple: 使用 JavaScript, HTML 和 CSS 构建跨平台的桌面应用
. A lot of friends also want to try using a front-end technology to do a desktop application, but often when installed directly on the error, most errors are:
1 |
Error: read ECONNRESET |
Solution
The solution is simple, if you are installing fail, then put node_modules
the electron
deleted, and then begin the following procedure again.
-
Set Taobao mirror source (recommended nrm use, this step is to ensure that no other dependencies error)
1
2npm install -g nrm
nrm use taobao -
Set the environment variables and installation
1
2
3
4
5And wait for it.
In-depth study
Through the above settings basically solved the problem of Electron installed, and now we can look into it and see how it was resolved. First we enter its source code , which has a npm this folder, this path is stored Electron npm rely on. Open look you will find only a few files, yes Electron dependencies so something.
So such a point of how things do cross-platform applications it? First, look at the package.json
file, for easy viewing, I copied a copy, as follows:
1 |
{ |
内容很少,但有2个部分很重要。一个是script
,可以看到里面有一个postinstall
的钩子命令,这条命令会在下载完依赖以后执行一下,也就说当依赖安装完后会执行node install.js
。另外一个重要的部分就是bin
,它指定了运行全局依赖时的入口文件,也就是cli.js
文件,我们稍后再说这个。
先简单的看一下install.js
,里面最主要的部分是调用了方法downloadArtifact
,用来下载跟平台相关的Electron可执行文件。下载完后调用extractFile
方法,把文件解压了,最后在path.txt
中把执行文件的路径写进去,这个路径下是不同平台下的可执行文件的路径。
最后我们看一下他是从哪里下载的。首先downloadArtifact
方法是在@electron/get依赖里面。我们进入到src/index
中。
此时我们可以看到url是通过getArtifactRemoteURL
方法获取的,然后我们看一下getArtifactRemoteURL
方法,源码在这里。
在getArtifactRemoteURL
方法中,可以看到,基础路径base
是通过mirrorVar
函数返回的,默认情况是没有nightly的,所以默认情况下是下面这个样子的:
1 |
process.env[`NPM_CONFIG_ELECTRON_MIRROR`] || |
而我们很少传入env的,options也没有mirror,所以通常是defaultValue
,具体值如下:
综上,我们可以看到默认情况下安装的时候会在github的release处下载一个平台相关的可执行文件。但是往往在国内github会很慢,所以这就导致了下载失败的问题,如果我们的env中传入ELECTRON_MIRROR
,那就会走该值所对应的地址,通常我们使用淘宝的镜像http://npm.taobao.org/mirrors/electron
。
同样的,在构建Windows系统的时候可能会用到依赖windows-build-tools
,该依赖会安装一个Python,这时可以使用淘宝的镜像文件会更快一些:
1 |
|
淘宝更多的开源软件的镜像可以参考这里。
启动过程
下载过程基本上我们已经明白了,现在说一下启动过程。一般启动Electron的时候调用的命令是electron .
,而electron命令其实是调用依赖包中的cli.js文件,该文件内容如下:
1 |
|
其中var electron = require('./')
的时候是引入当前文件夹下的index.js
文件,内容如下:
1 |
var fs = require('fs') |
index.js
Few contents of the documents, mainly the return address of a string, which is the path dist file in the current folder path of the executable file. Remember to download after path.txt
written inside the path of an executable file it?
We go back to cli.js
the file, you can see from the code, which starts a child process, started Electron executable file with the child, and the parameters passed into it. Finally, if the main process is interrupted or an error occurs, then put the child to kill. Of course, executable files, you can also double-click dist down, it will start a default page.