electron
electron 是 github 开发的 一款可以利用 Web 技术 开发跨平台桌面应用的框架,最初是 Github 发布的 Atom 编辑器衍生出的 Atom Shell,后更名为 Electron 。Electron 提供了一个能通过 JavaScript 和 HTML 创建桌面应用的平台,基于 nodejs
快速开始
前提
必须安装node 环境
全局安装 electron
sudo npm install -g electron
#可能会出现安装失败,使用 cnpm
文件结构
your-app
├── package.json
├── main.js
└── index.html
package.json 文件简单写:
{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js"
}
main.js 为入口:
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
// 保持一个对于 window 对象的全局引用,如果你不这样做,
// 当 JavaScript 对象被垃圾回收, window 会被自动地关闭
let win
function createWindow () {
// 创建浏览器窗口。
win = new BrowserWindow({width: 800, height: 600})
// 然后加载应用的 index.html。
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// 打开开发者工具。
win.webContents.openDevTools()
// 当 window 被关闭,这个事件会被触发。
win.on('closed', () => {
// 取消引用 window 对象,如果你的应用支持多窗口的话,
// 通常会把多个 window 对象存放在一个数组里面,
// 与此同时,你应该删除相应的元素。
win = null
})
}
// Electron 会在初始化后并准备
// 创建浏览器窗口时,调用这个函数。
// 部分 API 在 ready 事件触发后才能使用。
app.on('ready', createWindow)
// 当全部窗口关闭时退出。
app.on('window-all-closed', () => {
// 在 macOS 上,除非用户用 Cmd + Q 确定地退出,
// 否则绝大部分应用及其菜单栏会保持激活。
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// 在macOS上,当单击dock图标并且没有其他窗口打开时,
// 通常在应用程序中重新创建一个窗口。
if (win === null) {
createWindow()
}
})
// 在这文件,你可以续写应用剩下主进程代码。
// 也可以拆分成几个文件,然后用 require 导入。
index.html文件为正常的html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
test
</body>
</html>
这样就算一个桌面基本写完了
在开发目录下输入命令 electron . 运行 electron程序
官方给出了写好的示例 需要安装 git
$ git clone https://github.com/electron/electron-quick-start
$ cd electron-quick-start
$ npm install
$ npm start
这样一个 electron 构建的桌面程序就开始了