electron 基于 Node.js 和谷歌瀏覽器內(nèi)核,可以輕松使用 Javascript 來構(gòu)建一個跨平臺的應(yīng)用程序瞧剖,支持 Windows拭嫁、MacOS、Linux 三個平臺抓于。
微軟著名的 Vistual Studio Code 就是基于 electron 開發(fā)的, 這里再推薦一個基于 electron 開發(fā)的全平臺遠(yuǎn)程終端 Termius做粤, 在 Windows 下可以媲美 Xshell 工具。
官方圖片
下面開始進(jìn)入 electron 學(xué)習(xí)
安裝 Node.js
訪問官網(wǎng)
選擇合適的平臺下載安裝
查看 Node.js 是否成功安裝
# 查看 node 版本信息
node -v
# 查看 npm 版本信息
npm -v
上面兩個看到版本信息捉撮,說明已經(jīng)安裝成功了怕品!
創(chuàng)建一個 electron 應(yīng)用
- 在 workspace 下新建一個目錄
mkdir genesis
- 進(jìn)入目錄使用 npm 初始化
cd genesis
npm init
之后按照提示填寫,可以全程回車鍵,注意 entry point 默認(rèn)指定 index.js
執(zhí)行完成之后會生成 package.json
配置文件巾遭,看一下配置文件的內(nèi)容
{
"name": "genesis", # 項(xiàng)目名稱
"version": "1.0.0", # 版本號
"description": "", # 描述
"main": "main.js", # 入口文件, 默認(rèn)是 index.js
"scripts": {
"start":"electron .", # 啟動腳本肉康,指定 electron 運(yùn)行時
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
注意 配置文件中需要在 scripts
添加啟動腳本,并指定 electron
運(yùn)行時灼舍。
- 安裝 electron
npm install --save-dev electron
- main.js
const { app, BrowserWindow } = require('electron')
function createWindws() {
let win = new BrowserWindow({
width:800,
height:600,
webPreferences:{
nodeIntegration:true,
}
})
// 加載 index.html
win.loadFile('index.html')
// 打開開發(fā)者工具
win.webContents.openDevTools()
}
// 準(zhǔn)備好之后調(diào)用創(chuàng)建窗口
app.whenReady().then(createWindws)
// 關(guān)閉后退出
app.on('windows-all-colsed',()=>{
// 在 MacOS 上不是真正退出吼和,保持激活
if (process.platform != 'darwin') {
app.quit()
}
})
app.on('activate',()=>{
// 在macOS上,當(dāng)單擊dock圖標(biāo)并且沒有其他窗口打開時骑素,
// 通常在應(yīng)用程序中重新創(chuàng)建一個窗口炫乓。
if (BrowserWindow.getAllWindows().length == 0) {
createWindws()
}
})
- index.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</body>
</html>
- 啟動
npm start
好了,到這里就可以看到剛才創(chuàng)建的應(yīng)用程序了献丑。
參考資料