package.json
文件.npm init
初始化项目目录npm init // 或者 npm init -y
package.json
中编写一个start
脚本{ "name": "helloelectron", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "start": "electron .", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }
npm install --save electron
package.json
中的main
脚本的进程是主进程。ipcMain
模块接收渲染进程和向渲染进程发送消息。BrowserWindow
类开启一个渲染进程并将这个实例运行在该进程中,当一个BrowserWindow
实例被销毁后,相应的渲染进程也会被终止。ipcRenderer
模块接收主进程和向发送主进程发送消息。// app能够理解为主进程 // BrowserWindow用于建立渲染进程 const {app, BrowserWindow} = require('electron') app.on('ready', function createWindow () { // 能够建立多个渲染进程 let win1 = new BrowserWindow({ width: 1024, height: 768 }) let win2 = new BrowserWindow({ width: 1024, height: 768 }) // 渲染进程中的web页面能够加载本地文件 win1.loadFile('index.html') // 也能够加载远程页面 win2.loadURL('http://www.baidu.com') // 记得在页面被关闭后清除该变量,防止内存泄漏 win1.on('closed', function () { win1 = null }) win2.on('closed', () => { win2 = null }) }) // 页面所有关闭后关闭主进程,这里在不一样平台可能有不一样的处理方式,这里不深刻研究 app.on('window-all-closed', () => { app.quit() })
// index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>electron应用</title> </head> <body> <script> const fs = require('fs') fs.readFile('./demo.txt', function (err, data) { document.write(data) }) </script> </body> </html>
npm start
运行应用npm start
运行应用,那如何将应用分发给他人呢,下面简单介绍Windows平台的方式复制node_modules/electron/dist
目录下的文件到任意文件夹yourapp
css
复制你的项目文件到yourapp/resources/app
下html
删除yourapp/resources/default_app.asar
文件前端
运行yourapp/electron.exe
node
<script> const fs = require('fs') const path = require('path') fs.readFile(path.resolve(__dirname, 'demo.txt'), function (err, data) { document.write(data) }) </script>
【完】web
做者简介:叶茂,芦苇科技web前端开发工程师,表明做品:口红挑战网红小游戏、服务端渲染官网。擅长网站建设、公众号开发、微信小程序开发、小游戏、公众号开发,专一于前端领域框架、交互设计、图像绘制、数据分析等研究。 一块儿并肩做战: yemao@talkmoney.cn 访问 www.talkmoney.cn 了解更多npm