我有一个 Electron+React 项目,当我将 fs 或 path 模块导入到我的 React 组件文件中时出现错误。
preload.js 中的 contextBridge 也不起作用,当我在 app.js 中使用 window.api 时,会出现未定义的情况。
app.js
const { dialog } = require('electron');
const fs = require('fs');
错误
ERROR in ./src/App.js 16:11-24
Module not found: Error: Can't resolve 'fs' in '/Users/lotso/Documents/workspace/my-app/src'
ERROR in ./node_modules/electron/index.js 1:11-24
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
main.js内容
const { app, BrowserWindow } = require('electron')
const path = require('node:path')
const url = require('url');
const mode = process.argv[2];
function createWindow () {
const mainWindow = new BrowserWindow({width: 1000,height: 800,darkTheme: true,fullscreenable: false,
webPreferences: {
nodeIntegration: false,
preload: path.resolve(__dirname, 'preload.js'),
contextIsolation: false,
}
})
//dev or production
if(mode === 'dev') {
mainWindow.loadURL("http://localhost:3000/")
} else {
mainWindow.loadURL(url.format({
pathname:path.join(__dirname, './build/index.html'),
protocol:'file:',
slashes:true
}))
}
// mainWindow.webContents.openDevTools();
}
app.whenReady().then(() => {
createWindow()
})
预加载.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('api', {
openDialog: () => ipcRenderer.send('open-dialog'),
receiveDialogPaths: (callback) => ipcRenderer.on('selected-files', (event, paths) => callback(paths))
});
找到一些解决方案,但不起作用
// webpack.config.js
module.exports = {
...
// resolve fs or path module,
resolve: {
extensions: ['.js', '.jsx'],
fallback: {
"fs": require.resolve('fs'),
"path": require.resolve("path"),
"electron": require.resolve('electron'),
}
},
试试这个
const fs = require('node:fs')