electron使用过程中方法和坑

前言

刚今天把electron11版本集成到vueCli4.5创建的项目中,这里记录一下在集成过程中和平时使用时遇到的坑

问题:渲染线程renderer中引入Electron报错

报错内容:

fs.existsSync is not a function

原因:

因为webpack默认产出目标是web平台的js,其混淆了nodejs的标准模块系统,导致引入nodejs的模块时出现问题。

解决办法:

Error while importing electron in react | import { ipcRenderer } from 'electron'
Requiring electron outside of main.js causes a TypeError

即通过使用window.require代替require来引入electron,因为前者不会被webpack编译,在渲染进程require关键字就是表示node模块的系统;

其实,更佳的解决方案是通过webpack自身来帮我们解决,即修改webpack提供的target产出目标为electron,即:

修改electron主线程webpack的target配置项为electron-main
修改electron渲染线程的webpack的target配置项为electron-renderer
这样就可以更好的解决上面的问题。

方法:在浏览器环境中使用 nodejs api

electron将nodejs api挂载在了window对象上,来与底层进行通信,所以需要调用window上的require函数来引入 nodejs 包。

const electron = window.require('electron')
const process = window.require('process')
const fs = window.require('fs')
const Https = window.require('https')

方法:在浏览器环境中使用app对象

在electron主进程中使用app对象直接require electron就行了

const { app } = require('electron')

但是在渲染进程中使用app对象则需要这样引入:

const electron = window.require('electron')
const app = electron.remote.app
原文地址:https://www.cnblogs.com/shuiche/p/14173882.html