起步,helloworld(仿官网示例)
目标目录结构
|--demo01 | ---- package.json 程序依赖和运行脚本文件 | ---- main.js 程序入口文件 | ---- index.html 程序界面入口文件
创建package.json文件
# 全局安装electron,方便后续运行 npm install electron -g # 创建项目目录 mkdir demo01 && cd demo01 yarn init # 一路回车,直到成功生成package.json mkdir main.js mkdir index.html
编辑package.json
// 指定程序入口文件 "main": "main.js", // 添加项目启动脚本 "scripts": { "start": "electron ." }, // 添加程序依赖 "dependencies": { "electron": "^1.8.4" }
编辑main.js
var electron = require('electron'); var app = electron.app; // 鬼应用实例 var BrowserWindow = electron.BrowserWindow; // gui窗口 // 上面三行可简写为 // var { app, BrowserWindow } = require('electron); // 保持一个对于 window 对象的全局引用,不然,当 JavaScript 被 GC,window 会被自动地关闭 var mainWindow = null; // 当所有窗口被关闭了,退出。 app.on('window-all-closed', function () { // 在 OS X 上,通常用户在明确地按下 Cmd + Q 之前 // 应用会保持活动状态 if (process.platform != 'darwin') { app.quit(); } }); // 当 Electron 完成了初始化并且准备创建浏览器窗口的时候,这个方法就被调用 app.on('ready', function () { // 创建浏览器窗口。 mainWindow = new BrowserWindow({ width: 800, height: 600 }); // 加载应用的 index.html mainWindow.loadURL('file://' + __dirname + '/index.html'); // 打开开发工具 mainWindow.openDevTools(); // 当 window 被关闭,这个事件会被发出 mainWindow.on('closed', function () { // 取消引用 window 对象,如果你的应用支持多窗口的话, // 通常会把多个 window 对象存放在一个数组里面, // 但这次不是。 mainWindow = null; }); });
编辑index.html
<!DOCTYPE html> <html> <head> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> We are using io.js <script>document.write(process.version)</script> and Electron <script>document.write(process.versions['electron'])</script>. </body> </html>
安装依赖,启动程序
# 安装依赖,也可以使用npm install yarn install # 启动程序 npm start