Electron教程 (三)创建第一个helloworld应用

1,181 阅读1分钟

一、初始化package.json

npm init

electron项目即是一个node项目,使用package.json来配置包管理

二、新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>electron-demo</title>
</head>
<body>
    <h1>helloworld</h1>
</body>
</html>

这个页面是首页展示的内容,很简单就一个纯html静态页面

创建入口文件index.js

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

function createWindow(){
    // 创建浏览器窗口
    win = new BrowserWindow({width: 800,height: 600})
    // 加载应用的index.html
    win.loadFile('index.html')
}
app.on('ready',createWindow)

这个index.js是应用的入口文件,使用electron库下面的app及BrowserWindow类,使用app类的on方法来监听应用的状态,当状态为ready时,执行createWindow方法,createWindow方法中,创建一个BrowserWindow类的实例,并初始化客户端的宽度和高度,然后执行实例的loadFile方法,加载上面创建好的index.html文件。

启动electron

electron .

好了,运行效果如下:

恭喜您,第一个electron客户端就创建好了!