Electron 入门学习案例
electron 是桌面端的一个框架。可以把 html+js+css 封装成为一个 exe 或者 其他平台的应用程序。很好的实现了跨平台。并且开发效率很快。
初始化环境
初始化 npm 环境使用命令npm init -V
,然后可以生成一个 package.json
的文件。
npm环境初始化以后进而要安装我们的主角 Electron 使用命令 npm i electron
# 全局安装
npm install electron -g
# 安装到本地的项目中
npm install electron -D
这就初始化完毕接下来就是配置启动的命令和热更新的配置
编写基本文件
创建文件
index.js
启动文件
const { app, BrowserWindow } = require('electron')
const createWindow = () => {
const win = new BrowserWindow({
width: 1000, // 宽
height: 600, // 高
});
// 加载资源数据 (index.html 文件是要自己手动创建的)
win.loadFile('./index.html');
// 打开发者工具
// win.webContents.openDevTools();
}
app.whenReady().then(createWindow)
创建
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Electron</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
到这一步其实就可以正常启动 electron 的第一个小 demo 了。不过启动的命令我们最好可以配置到 node 中
配置启动命令
这个就是 electron 的启动命令electron .
配置到 node 下面的就是 npm init -V
生成的 package.json
文件
{
"name": "electron-basics",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// 在这里配置启动的命令
"start": "electron ."
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^20.1.3",
"nodemon": "^2.0.19"
}
}
然后在 cmd
窗口运行 npm run start
(如果运行命令是 start
的时候 npm start
== npm run start
)
到这一步其实就可以了,但是为了更好的编写代码我们肯定要配置一下热更新的。
热更新
安装插件 nodemon
运行命令 npm i nodemon
然后配置到我们的 package.json
中。
{
"name": "electron-basics",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// 在这里配置启动的命令
"start": "nodemon --exec electron ."
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^20.1.3",
"nodemon": "^2.0.19"
}
}
大功告成!!!