将create-react-app与electron创建出的一个项目中。React中无法使用electron
当在React中使用require(‘electron’)时就会报
Uncaught TypeError: fs.existsSync is not a function at getElectronPath (index.js:8)
因为React中无法使用Node.js的模块.
所以,百度了下:方案如下
- 创建renderer.js文件
global.electron = require('electron');
- 修改main.js文件
修改创建浏览器的入口代码,添加preload配置项。将renderer.js作为预加载文件
win = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
javascript: true,
plugins: true,
nodeIntegration: true, // 是否集成 Nodejs
webSecurity: false,
preload: path.join(__dirname, '../public/renderer.js') // 但预加载的 js 文件内仍可以使用 Nodejs 的 API
}
})
-
在React组件中如下使用electron
const electron = window.electron;
因为要使用进程通讯,所以可以在渲染进