Theme NexT works best with JavaScript enabled
0%

第一个Electron项目

^ _ ^

前提条件

在使用Electron进行开发之前,您需要安装 Node.js。
要检查 Node.js 是否正确安装,请在您的终端输入以下命令:

1
2
node -v
npm -v

创建应用程序

首先创建一个文件夹并初始化 npm 包。

1
2
mkdir hello_electron && cd hello_electron
npm init

init初始化命令会提示您在项目初始化配置中设置一些值,最后项目下生成的package.json文件应该像这样:

1
2
3
4
5
6
7
8
{
"name": "hello_electron",
"version": "1.0.0",
"description": "Hello World!",
"main": "main.js",
"author": "LuckyQ",
"license": "MIT"
}

然后,将 electron 包安装到应用的开发依赖中。

1
npm install --save-dev electron

大家都知道国内直接使用 npm 的官方镜像是非常慢的,这里推荐使用淘宝 NPM 镜像。
你可以使用淘宝定制的 cnpm (gzip 压缩支持) 命令行工具代替默认的 npm:

1
npm install -g cnpm --registry=https://registry.npm.taobao.org

这样就可以使用 cnpm 命令来安装模块了:

1
cnpm install electron --save-dev

最后,在您的 package.json配置文件中的scripts字段下增加一条start命令:

1
2
3
4
5
{
"scripts": {
"start": "electron ."
}
}

任何 Electron 应用程序的入口都是 main 文件。 这个文件控制了主进程,它运行在一个完整的Node.js环境中,负责控制您应用的生命周期,显示原生界面,执行特殊操作并管理渲染器进程(稍后详细介绍)。

执行期间,Electron 将依据应用中 package.json配置下main字段中配置的值查找此文件。要初始化这个main文件,需要在您项目的根目录下创建一个名为main.js的空文件。

start命令能让您在开发模式下打开您的应用

1
npm start

创建页面

在可以为我们的应用创建窗口前,我们需要先创建加载进该窗口的内容。 在 Electron 中,每个窗口中无论是本地的HTML文件还是远程URL都可以被加载显示。

此教程中,您将采用本地HTML的方式。 在您的项目根目录下创建一个名为index.html的文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</body>
</html>

在窗口中打开页面

现在您有了一个页面,将它加载进应用窗口中。 要做到这一点,你需要 两个Electron模块:

  • app 模块,它控制应用程序的事件生命周期。
  • BrowserWindow 模块,它创建和管理应用程序窗口。

因为主进程运行着Node.js,您可以在文件头部将他们导入作为公共JS模块:

1
const { app, BrowserWindow } = require('electron')

然后,添加一个createWindow()方法来将index.html加载进一个新的BrowserWindow实例。

1
2
3
4
5
6
7
8
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})

win.loadFile('index.html')
}

接着,调用createWindow()函数来打开您的窗口。

1
2
3
app.whenReady().then(() => {
createWindow()
})

管理窗口的生命周期

关闭所有窗口时退出应用

1
2
3
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})

通过预加载脚本从渲染器访问Node.js

现在,最后要做的是输出Electron的版本号和它的依赖项到你的web页面上。

预加载脚本在渲染器进程加载之前加载,并有权访问两个 渲染器全局 (例如 window 和 document) 和 Node.js 环境。创建一个名为 preload.js 的新脚本如下:

1
2
3
4
5
6
7
8
9
10
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}

for (const dependency of ['chrome', 'node', 'electron']) {
replaceText(`${dependency}-version`, process.versions[dependency])
}
})

要将此脚本附加到渲染器流程,请在你现有的 BrowserWindow 构造器中将路径中的预加载脚本传入 webPreferences.preload 选项。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 在文件头部引入 Node.js 中的 path 模块
const path = require('path')
// 修改现有的 createWindow() 函数
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

win.loadFile('index.html')
}

完整代码

main.js

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
const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});

win.loadFile('index.html');
}

// 在 Electron 中,只有在 app 模块的 ready 事件被激发后才能创建浏览器窗口
app.whenReady().then(() => {
createWindow();
});

// 关闭所有窗口时退出应用
app.on('window-all-closed', function () {
if (process.platform !== 'darwin')
app.quit();
});

preload.js

1
2
3
4
5
6
7
8
9
10
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}

for (const dependency of ['chrome', 'node', 'electron']) {
replaceText(`${dependency}-version`, process.versions[dependency])
}
});

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--index.html-->

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.

<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>