版权声明:本文为博主原创文章,请转载时注明出处,欢迎浏览! https://blog.csdn.net/leemboy/article/details/84720297
Electron简介:
Electron是一种运行环境库,我们可以基于此,用HTML、JS和CSS写桌面应用。
PC端的UI交互,主要有web应用和桌面应用。具体采用哪种方式,主要看系统的应用场景,哪个更合适用哪个。
对于Web应用:
优点:
- 部署、升级方便。用户通过浏览器就可以访问;
- HTML/JS/CSS编写,方便且高效;
- windows、linux都支持;
Electron环境搭建
1、安装node.js。node官网地址:https://nodejs.org/en/
2、在windows 命令行下检查node是否安装成功。分别输入 node -v, npm -v 。如果出现 node 和 npm 的版本号,则转下一步。否则转第一步。
3、在命令行,下载淘宝镜像命令工具 cnpm。
npm install cnpm -g --registry=http://registry.npm.taobao.org
4、用 cnpm 命令安装 electron。
cnpm install electron -g
检查electron版本
做一个简单的项目看下electron程序的效果。
新建一个项目目录,名字就叫desktopApp
在该目录下,新建三个文件,结构如下:
desktopApp/
├── 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')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
在index.html文件中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</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>
运行,在这个项目目录下面运行一条命令就可以启动app,注意,不能丢掉 点号 .
E:\electron\desktopApp>electron .