![f310693dc42dbcbb06bda61518ec0c71.png](https://i-blog.csdnimg.cn/blog_migrate/1d6b59ffb7f7d1f3f101c120f4f41867.jpeg)
最近在研究前端大型项目中要怎么管理模块间通信,本文记录研究 VSCode 中通信机制的过程,主要包括 IPC 部分吧。
# Electron 的 通信机制
我们知道 Electron 是基于 Chromium + Node.js 的架构。同样基于 Chromium + Node.js 的,还有 NW.js,我们先来看看它们之间有什么不一样吧。
## Electron 与 NW.js
说到 Node.js 的桌面应用,基本上大家都会知道 Electron 和 NW.js。例如 VsCode 就是基于 Electron 写的,而小程序开发工具则是基于 NW.js 来开发的。
我们知道,Node.js 和 Chromium 的运行环境不一样,它们的 JavaScript 上下文都有一些特有的全局对象和函数。在 Node.js 中包括 module、process、require等,在 Chromium 中会有 window、 documnet等。
那么,Electron 和 NW.js 都分别是怎样管理 Node.js 和 Chromium 的呢?
## NW.js 内部架构
NW.js 是最早的 Node.js 桌面应用框架,架构如图:
![c673e4e86752dd03a21d52508c2f8e29.png](https://i-blog.csdnimg.cn/blog_migrate/cd0563748997f6507b773aaec7206632.png)
在 NW.js 中,将 Node.js 和 Chromium 整合在一起使用,其中做了几件事情,我们来分别看下。
- Node.js 和 Chromium 都使用 V8 来处理执行的 JavaScript,因此在 NW.js 中它们使用相同的 V8 实例。
- Node.js 和 Chromium 都使用事件循环编程模式,但它们用不同的软件库(Node.js 使用 libuv,Chromium 使用 MessageLoop/Message-Pump)。NW.js 通过使 Chromium 使用构建在 libuv 之上的定制版本的 MessagePump 来集成 Node.js 和 Chromium 的事件循环。
![2213aa766d1a8a31a9ed744342f94064.png](https://i-blog.csdnimg.cn/blog_migrate/dde5b21602448bb4e16a088d78dec2bc.png)
3. 整合 Node.js 的上下文到 Chromium 中,使 Node.js 可用:
![2d9ccc8c55e77eb3bdf0652d2ca51ce6.png](https://i-blog.csdnimg.cn/blog_migrate/d0d9d1d431c1d3a8e6c967a6a1fbb84f.jpeg)
因此,虽然 NW.js 整合了 Node.js 和 Chromium,但它更接近一个前端的应用开发方式,它的入口是 index.html:
![fbf4188a17e03530090b3b96550ae25e.png](https://i-blog.csdnimg.cn/blog_migrate/b86bd8ebae54e0c93e9b807c11b42b00.png)
## Electron 内部架构
Electron 强调 Chromium 源代码和应用程序进行分离,因此并没有将 Node.js 和 Chromium 整合在一起。
在 Electron 中,分为主进程(main process)和渲染器进程(renderer processes):
- 主进程:一个 Electron 应用中,有且只有一个主进程(package.json 的 main 脚本)
- 渲染进程:Electron 里的每个页面都有它自己的进程,叫作渲染进程。由于 Electron 使用了 Chromium 来展示 web 页面,所以 Chromium 的多进程架构也被使用到
那么,不在一个进程当然涉及跨进程通信。于是,在 Electron 中,可以通过以下方式来进行主进程和渲染器进程的通信:
- 利用
ipcMain
和ipcRenderer
模块进行 IPC 方式通信