Electron 教程:第一个程序
先前我们已经为我们的项目创建了一个名为package.json的文件。现在我们使用Electron创建我们的第一个桌面应用程序。
创建一个名为main.js的新文件
const {app, BrowserWindow} = require('electron') //引入模块 const url = require('url') const path = require('path') let win function createWindow() { //定义创建窗体函数 win = new BrowserWindow({width: 800, height: 600}) //指定宽度和高度 win.loadURL(url.format ({ //加载index.html文件 pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) } app.on('ready', createWindow) //当触发ready事件的时候执行createWindow函数
创建另一个名为index.html的html文件。在其中输入以下代码。
<!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> We are using node <script>document.write(process.versions.node)</script>, Chrome <script>document.write(process.versions.chrome)</script>, and Electron <script>document.write(process.versions.electron)</script>. </body> </html>
使用以下命令运行此应用程序
$ electron ./main.js
这将会打开一个新的窗体。它看起来如下:
这个应用程序是如何工作的?
我们创建了一个主文件和一个HTML文件。主文件使用两个模块:app和BrowserWindow。app模块用于控制应用程序的事件生命周期,而BrowserWindow模块用于创建和控制浏览器窗口。
我们定义了一个createWindow函数,在这里我们创建了一个新的BrowserWindow,并为这个BrowserWindow附加了一个网址。这是我们运行应用程序时呈现并显示给我们的HTML文件。
我们在html文件中使用了一个原生的Electron对象过程。这个对象是从Node.js过程对象扩展而来的,包括了它的所有功能,同时也增加了更多的功能。