1.electron架构思考
在做electron桌面开发中,Electron+vue当下算是性价比的比较高的。但是electron算是小众开发,遇到问题,基本上就是掉进深坑,爬好久才出来。
为了做一个项目,我翻遍了国内好多网站。看到一篇好的文章。Electron 应用实战 (架构篇) 这篇还是很值得好好看看
其中一句话,我觉得讲的很有道理====》数据通讯方案决定整体的架构方案。
原因:Electron 有两个进程,分别为 main 和 renderer,而两者之间需要进行通讯,通讯机制不同。
1. 方案1 只是简单的通信,没有大数据量通信。
通常采用本身的自带方案,ipc方式 main 端有 ipcMain,renderer 端有 ipcRenderer,分别用于通讯。
缺点:不支持大数据通信和复杂的业务逻辑
2.用remote模块渲染进程直接调用主进程的进程
remote模块官方文档 https://electronjs.org/docs/api/remote
例如
主进程:
1 2 3 4 5 6 7 8 | // 主进程 mapNumbers.js exports.withRendererCallback = (mapper) => { return [1, 2, 3].map(mapper) } exports.withLocalCallback = () => { return [1, 2, 3].map(x => x + 1) } |
渲染进程
1 2 3 4 5 6 7 | // 渲染进程 const mapNumbers = require( 'electron' ).remote.require( './mapNumbers' ) const withRendererCb = mapNumbers.withRendererCallback(x => x + 1) const withLocalCb = mapNumbers.withLocalCallback() console.log(withRendererCb, withLocalCb) // [undefined, undefined, undefined], [2, 3, 4] |
3.Electron+vue一渲染进程直接调用主进程的方法
3.1创建项目
1 | vue init simulatedgreg/electron-vue my-project |
3.2安装依赖
3.3产生目录结构

1 2 3 4 5 6 | project/ ├── main │ ├── foo.js │ └── index.js └── renderer └── main.js |
1 | └── webpack.main.config.js |
3.4主进程=>创建 foo.js
1 2 3 4 5 6 7 8 9 | module.exports = { getTest1(){ return 'test1' ; }, getTest2(){ return 'test2' ; }, } |
3.4渲染进程=>main.js
1 2 3 4 5 6 7 8 9 10 11 | import Vue from 'vue' import axios from 'axios' import App from './App' import router from './router' import store from './store' //引入foo主进程 const foo = require( 'electron' ).remote.require( './foo' ); //将 foo 挂载到 vue 的原型上 Vue.prototype.foo = foo; |
3.5 landingPage.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script> export default { methods: { clickMethodInMainProcess() { console.log( '\n\n------ begin: ------' ) console.log( this .foo.getTest1()) console.log( this .foo.getTest2()) console.log( '------ end: ------\n\n' ) } } </script>el |
3.6 webpack增加新entry
在 .electron-vue/webpack.main.config.js 添加新entry
a good solution by editing the webpack.main.config.js
and manually adding every relative module as new entries.
1 2 3 4 5 6 | let mainConfig = { entry: { main: path.join(__dirname, '../src/main/index.js' ), foo: path.join(__dirname, '../src/main/foo.js' ) }, } |
参考:
https://github.com/SimulatedGREG/electron-vue/issues/291