一,安装
1. node 安装
- 去官网下载,一路下一步。
[node](https://nodejs.org/)
- 在命令行输入命令,验证安装
![]()
二, 创建项目
- 2.1 创建项目目录
mkdir electron-demo && cd electron-demo
- 2.2 初始化项目
npm init
- 一路回车,默认(
author 和 description 如果要打包必须填)
- 安装
electron:npm install --save-dev electron
- 在
package.json中的scripts里添加一项electron的启动脚本命令:"start":"electron ."
- 此时运行
npm start 会发生报错,因为没有入口文件 index.js
- 入口文件在
package.json中配置,可自定义
- 在目录中创建
index.js,继续执行npm start,此时electron已经启动,但是没有界面,因为我们没有创建窗口。
- 在目录中创建一个
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>Document</title>
</head>
<body>
electron-demo running
</body>
</html>
- 在
index.js中写入代码 //引入对象
const {app, BrowserWindow} = require('electron')
//创建窗体方法
const createWindow = ()=>{
const win = new BrowserWindow({
width:800,
height:600
})
//加载html
win.loadFile('index.html')
}
app.whenReady().then(()=>{
createWindow()
})
- 到此,程序已经可以运行看到
![]()
- 2.3 优化项目
// main.js
// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// 加载 index.html
mainWindow.loadFile('index.html')
// 打开开发工具
// mainWindow.webContents.openDevTools()
}
// 这段程序将会在 Electron 结束初始化
// 和创建浏览器窗口的时候调用
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(() => {
createWindow()
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 (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// 除了 macOS 外,当所有窗口都被关闭的时候退出程序。 There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
// In this file you can include the rest of your app's specific main process
// code. 也可以拆分成几个文件,然后用 require 导入。
三,理解概念
- 进程
- 主进程:
node进程,拥有完全操作系统访问权限。
electron模块
- 其余
node内置模块
- 以及通过
npm安装的第三方模块
- 渲染进程:网页进程
- 预加载脚本
- 拥有部分 html dom,node,electron 权限的脚本
webPreferences,contextBridge
- 在进程之间通信
四,深入方向
- 增加渲染进程的网页应用代码复杂度
- 深化与操作系统和 Node.js 的集成