Electron(13.1.2)+React(17.0.2)项目错误记录

报错:TypeError: fs.existsSync is not a function

在React项目中引用

const electron = require('electron');

替换为:

const electron = window.require('electron');

同时需要加入webPreferences配置:

const win = new BrowserWindow({
      width: 1000,
      height: 800,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true
      }
    })

使用例子:

const electron = window.require('electron');
const { remote } = electron;

class ReactNative extends React.Component {
    createOpenDialog = () => {
        remote.dialog.showOpenDialog({  
            properties: ['openFile', 'openDirectory']
        }).then(result => {  
            console.log(result.filePaths[0]);
        }).catch(err => {  
            console.log(err)
        })
    }
}

export default ReactNative;

preload.js

无法暴露API,请查看Electron v13的最新文档。

const { contextBridge } = require('electron')

contextBridge.exposeInMainWorld('myAPI', {
  desktop: true
})

打包

function createWindow () {
    // 打包时候使用
    win.loadURL(`file://${__dirname}/build/index.html`);
    
    // RN调试启动
    // win.loadURL('http://localhost:3000/')
}

package.json 配置,代码文件填入相应files中,否则打包不进去。

"build": {
    "appId": "xxx.xxx.xxx",
    "extends": null,
    "files": [
      "package.json",
      "main.js",
      "build/",
      "node_modules/",
      "src/"
    ],
    "mac": {
      "icon": "build/logo.png",
      "category": "public.app-category.developer-tools",
      "target": [
        "dmg"
      ]
    }
}

先构建React,再构建Electron

// 先执行
"build": "react-scripts build",

// 再执行
"build-electron": "electron-builder"

例子:

yarn build
yarn build-electron

你可能感兴趣的:(Electron(13.1.2)+React(17.0.2)项目错误记录)