在进行该章内容之前,我们假设你已经正确的创建了一个package.json文件以及安装完成electron.现在 我们通过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({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}))
}
app.on('ready', createWindow)
另外我们还需要创建一个index.html,并且在该文件里面写入下面的语句。
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<h1>Hello World</h1>
We are using node
<scrip>document.write(process.versions.node)</scrip>
Chrome
<script>
document.write(process.versions.chrome)
</script>
and Electron
<script>
document.write(process.versions.electron)
</script>
</body>
</html>
我们之后我们通过命令行输入如下的命令,却可运行应用。
$ electron ./main.js
它将会打开一个新的窗口,显示的内容如下图所示。
上面的应用工作原理
在我们创建的main.js文件当中包含两个模块,app和BrowerWindow。app 模块主要控制你应用的生命周期。而BrowerWindow主要用创建和控制窗口对象。
我们定义了一个createWindow函数。我们创建了一个新的BrowerWindow对象,并且将URL附加到该对象当中。index.html主要是我们将要呈现给用户的界面。