Electron Forge+React+TS项目使用ipcRenderer时出现fs/path模块找不到错误
问题根源
你在渲染进程(App.tsx)中直接import {ipcRenderer} from "electron",导致Webpack打包时尝试处理electron模块本身。而electron依赖Node.js核心模块(fs、path),这些模块在浏览器环境(渲染进程)中不存在,且Webpack 5不再默认提供这些模块的polyfill,因此抛出解析错误。
同时,直接开启nodeIntegration: true虽然能让渲染进程访问Node.js,但属于不安全的做法,且无法解决Webpack的打包解析问题。
正确解决方案:通过预加载脚本暴露API
Electron的预加载脚本运行在Node.js上下文与渲染进程之间的隔离环境,可安全访问Electron API,再通过contextBridge将需要的功能暴露给渲染进程。
1. 编写预加载脚本(preload.ts)
在项目src目录下创建或修改preload.ts,通过contextBridge暴露通知触发方法:
import { contextBridge, ipcRenderer } from 'electron'; // 暴露给渲染进程的API contextBridge.exposeInMainWorld('electronAPI', { showNotification: (data: { notificationTitle: string; notificationBody: string }) => { ipcRenderer.send('show-notification', data); } }); // 声明全局类型,让TypeScript识别window上的electronAPI declare global { interface Window { electronAPI: { showNotification: (data: { notificationTitle: string; notificationBody: string }) => void; }; } }
2. 修正主进程的窗口配置
修改主进程index.ts中的BrowserWindow配置,开启上下文隔离(默认已开启)并关闭nodeIntegration(安全最佳实践):
const mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY, contextIsolation: true, // 强制开启上下文隔离,确保安全 nodeIntegration: false // 关闭渲染进程的Node.js集成 }, });
3. 修改渲染进程代码(App.tsx)
不再直接导入electron模块,而是通过window对象访问预加载脚本暴露的API:
import React from 'react'; import NavBar from "./components/Navbar"; const App: React.FC = () => { const notificationData = { notificationTitle: 'Notification Title', notificationBody: 'Notification Body' } return ( <> <NavBar/> <h1>Hello there!</h1> <button onClick={() => window.electronAPI.showNotification(notificationData)}>Click me for notification</button> </> ) } export default App;
4. 配置Webpack忽略Node.js核心模块
在渲染进程的Webpack配置文件(webpack.renderer.config.ts)中,添加resolve.fallback和externals,告诉Webpack不要解析Node.js核心模块和electron模块:
import type { Configuration } from 'webpack'; const config: Configuration = { // ...其他默认配置 resolve: { fallback: { fs: false, path: false }, externals: { electron: 'commonjs electron' // 忽略electron模块的打包 } } }; export default config;
如果你的项目没有自定义Webpack配置,需要在forge.config.ts中关联上述配置:
import type { ForgeConfig } from '@electron-forge/shared-types'; import { WebpackPlugin } from '@electron-forge/plugin-webpack'; import { mainConfig } from './webpack.main.config'; import { rendererConfig } from './webpack.renderer.config'; const config: ForgeConfig = { packagerConfig: {}, rebuildConfig: {}, makers: [/* 保持原有配置 */], plugins: [ new WebpackPlugin({ mainConfig, renderer: { config: rendererConfig, entryPoints: [ { html: './src/index.html', js: './src/renderer.tsx', name: 'main_window', preload: { js: './src/preload.ts', }, }, ], }, }), ], }; export default config;
验证修复
执行npm run start启动项目,点击按钮即可触发桌面通知,且Webpack不会再抛出fs/path模块解析错误。
内容的提问来源于stack exchange,提问作者renegadedev

