前言
剛今天把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