- 安裝electron, electron-prebuilt
$ npm install cnpm -g --registry=http://registry.npm.taobao.org
$ cnpm install electron -g
$ cnpm install electron-prebuilt -g
- 安裝electron-packager, electron-builder, asar
$ cnpm install electron-packager -g
$ cnpm install electron-builder -g
$ cnpm install asar -g
- 初始化項(xiàng)目
$ cnpm init
執(zhí)行完后, 當(dāng)前目錄下生成package.json文件
{
"name": "own-runner",
"version": "1.0.0",
"description": "神器",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "PeopleName",
"license": "ISC"
}
- 添加index.html, index.js
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8"/>
<title>test</title>
</head>
<body>
Hello World!
<button id="button">點(diǎn)擊這里</button>
<script>
console.log(window)
var button = document.getElementById('button');
button.onclick = function(){
alert("Hello Electron!")
}
</script>
</body>
</html>
index.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
// 保存窗口對(duì)象的全局引用, 如果不這樣做, 當(dāng)JavaScript對(duì)象被當(dāng)做垃圾回收時(shí)届搁,window窗口會(huì)自動(dòng)關(guān)閉
let win
function createWindow () {
// 創(chuàng)建瀏覽器窗口.
win = new BrowserWindow({width: 800, height: 600,autoHideMenuBar :true})
win.setMenu(null);
// 加載項(xiàng)目的index.html文件.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
// 當(dāng)窗口關(guān)閉時(shí)候的事件.
slashes: true
}))
// 打開開發(fā)工具.
//win.webContents.openDevTools()
win.on('closed', () => {
// 取消引用窗口對(duì)象, 如果你的應(yīng)用程序支持多窗口贮配,通常你會(huì)儲(chǔ)存windows在數(shù)組中躬贡,這是刪除相應(yīng)元素的時(shí)候。
console.log("haha");
win = null
})
}
app.on('activate', () => {
console.log('activate')
if (win === null) {
createWindow()
} else {
win.show()
}
})
// 當(dāng)Electron完成初始化并準(zhǔn)備創(chuàng)建瀏覽器窗口時(shí)莺掠,將調(diào)用此方法
// 一些api只能在此事件發(fā)生后使用。
app.on('ready', createWindow)
// 當(dāng)所有窗口關(guān)閉時(shí)退出隅很。
app.on('window-all-closed', () => {
// 在macOS上,用得多的是應(yīng)用程序和它們的菜單欄升筏,用Cmd + Q退出。
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// 在macOS上瘸爽,當(dāng)點(diǎn)擊dock圖標(biāo)并且沒有其他窗口打開時(shí),通常會(huì)在應(yīng)用程序中重新創(chuàng)建一個(gè)窗口铅忿。
if (win === null) {
createWindow()
}
})
- 修改package.json
"scripts": {
"start": "electron .",
"pack": "electron-builder --dir",
"dist": "electron-builder"
},
"build": {
"appId": "隨意",
"win": {
}
},
- 打包或運(yùn)行
$ npm|cnpm|yarn install
$ npm|cnpm|yarn dist #dist目錄下生成exe文件
$ npm|cnpm|yarn start #運(yùn)行
Ref.
Electron: https://electronjs.org/docs