渲染进程(Renderer Process)
正如上节所了解,main.js
标识出了Electron渲染进程(Renderer Process)的HTML文件。渲染进程正是从mainWindow.loadURL()
调用开始的:
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
通过Node的url.format
方法,程序将Electron的__dirname
变量和index.html
文件关联起来。这个变量指向了程序的根目录。
我们来看看index.html
文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<!-- All of the Node.js APIs are available in this renderer process. -->
We are using Node.js
<script>document.write(process.versions.node)</script>, Chromium
<script>document.write(process.versions.chrome)</script>, and Electron
<script>document.write(process.versions.electron)</script>.
</body>
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</html>
如你所见这是一个很基础的HTML文件,但是有些要点对你理解Electron的工作原理非常重要。
首先来看这些用来调用Node进程API的script标签:
<!-- All of the Node.js APIs are available in this renderer process. -->
We are using Node.js
<script>document.write(process.versions.node)</script>, Chromium
<script>document.write(process.versions.chrome)</script>, and Electron
<script>document.write(process.versions.electron)</script>.
如注释所述,你可以在渲染进程调用Node的API,因此可以像上述HTML代码一样直接使用Node的API。这个例子中的代码调用Node的API显示出了当前应用的Node、Chromium和Electron的版本,显示结果如图3.2所示:
Figure 3-2.The starter Electron application, the version numbers dynamically added
这些代码不是应用必不可少的,但是对我们理解Electron原理很有帮助。
另一个index.html
文件中的要点是底部的script标签:
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
这里引入了renderer.js
文件,大多情况下这里是应用的JavaScript代码运行起点。renderer.js
文件目前只有几行注释:
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
总结
构建Electron应用的方式有很多。如果你用最基础的方法(只使用原生JavaScript代码而不用任何框架),这些文件都是你要关注的。由于可选用的框架太多,我们不可能在本书中讲述如何使用框架。本书的宗旨是使用简单的JavaScript代码讲述Electron的特性,使用Electron Quick Start为学习出发点有助于贯穿宗旨。