是什么:Electron是npm上的一个开源库,似乎也可以理解为一个“浏览器”,它可以通过Node.js来实现桌面应用程序。
为什么要用它:传统的桌面应用程序多半是Java、C#、Delphi等后台语言编写的,有了Electron后,掌握Node.js也可以创建桌面应用程序了。
类似:NW.js(由node-webkit改名而来,但根据所查资料显示,NW坑比较多,现在更倾向用Electron)。
前提:nodejs和npm环境。
安装:
1.由于本地无法从npmjs上安装electron,所以第一步需要先安装cnpm,这样就能够从淘宝的npm镜像中获取想要的包了。
npm install -g cnpm --registry=https://registry.npm.taobao.org
2.在项目根目录安装electron
cnpm install electron --save-dev
代码:
./index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Try Everything</title> <style type="text/css"> body{ /*background-color: wheat;*/ } h5{ color: PaleVioletRed; } </style> </head> <body> <h5> I messed up tonight, I lost another fight</br> 刚搞砸了今晚 却又遭遇失败</br> I still mess up but I'll just start again</br> 陷入混乱但也想不断重来</br> I keep falling down, I keep on hitting the ground</br> 不断跌倒不断触地失败</br> I always get up now to see what's next</br> 也要重新站起来面对接下来的挑战</br> Birds don't just fly, they fall down and get up</br> 鸟儿亦不会总在翱翔 也会有起落受伤</br> Nobody learns without getting it won</br> 人生亦是在坚持到胜利之后方才寻得答案</br> I won't give up, no I won't give in</br> 我不会放弃 也绝不妥协投降</br> Til I reach the end, then I'll start again</br> 直到到达终点 然后迈向新的战场</br> </h5> </body> </html>
./main.js
const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; let mainWindow; function createWindow(){ mainWindow = new BrowserWindow({ 400, height:340, autoHideMenuBar:true, icon:"./favicon.ico" }); mainWindow.loadURL('file://' + __dirname + '/index.html'); // mainWindow.webContents.openDevTools(); mainWindow.on('closed', function () { mainWindow = null; }); } app.on('ready',createWindow); app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit(); } });
package.json
{ "name": "HelloWorld", "version": "0.0.1", "main": "./main.js", "scripts": { "start": "electron main.js" }, "devDependencies": { "electron": "^1.6.11" } }
另外还有一个图标文件
./favicon.ico
运行:
electron main.js
运行效果: