多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
#### 因为博主突然就想要研究electronjs了所以更新一波,博主随缘研究技术,可能研究一半就去看其他的了。 #### 前言:[Electron 文档](https://electronjs.org/docs/tutorial/installation)其实说的很清楚了,并且有很多很多的注释,这边我在给他重复一遍 # :-: **预热** 博主npm 因为是win7系统所以老是会安装失败。这边就使用[yarn](https://yarn.bootcss.com/),不知道yarn和npm区别的同学,这边博主给你们准备了一篇[npm和yarn区别文章](https://yarnpkg.com/zh-Hans/docs/migrating-from-npm),是不是很**贴心**。 # :-: **正文** > 我们直接说代码,先建立一个package.json。 ``` yarn init ``` 或者 ``` npm init ``` > 直接把文件里面东西清空,然后写入下方代码。 ``` { "name": "your-app", "version": "0.1.0", "main": "main.js", "scripts": { "start": "electron ." } } ``` > 安装Electron ``` yarn add electron ``` 或者 ``` npm install electron ``` > 我们在根目录新建一个main.js ``` const { app, BrowserWindow } = require('electron') // 保持对window对象的全局引用,如果不这么做的话,当JavaScript对象被 // 垃圾回收的时候,window对象将会自动的关闭 let win function createWindow () { // 创建浏览器窗口。 win = new BrowserWindow({ width: 800, height: 600 }) // 然后加载应用的 index.html。 win.loadFile('index.html') // 打开开发者工具 win.webContents.openDevTools() // 当 window 被关闭,这个事件会被触发。 win.on('closed', () => { // 取消引用 window 对象,如果你的应用支持多窗口的话, // 通常会把多个 window 对象存放在一个数组里面, // 与此同时,你应该删除相应的元素。 win = null }) } // Electron 会在初始化后并准备 // 创建浏览器窗口时,调用这个函数。 // 部分 API 在 ready 事件触发后才能使用。 app.on('ready', createWindow) // 当全部窗口关闭时退出。 app.on('window-all-closed', () => { // 在 macOS 上,除非用户用 Cmd + Q 确定地退出, // 否则绝大部分应用及其菜单栏会保持激活。 if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { // 在macOS上,当单击dock图标并且没有其他窗口打开时, // 通常在应用程序中重新创建一个窗口。 if (win === null) { createWindow() } }) // 在这个文件中,你可以续写应用剩下主进程代码。 // 也可以拆分成几个文件,然后用 require 导入。 ``` > 然后我们在新建一个index1.html和index2.html ``` /*index1.html*/ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> <a href="./index2.html">index2.html</a> <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> ``` ``` /*index2.html*/ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> <a href="./index1.html">index1.html</a> <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> ``` > 最后我们执行 ``` npm start ``` #### PS:Electron初探完成