The formed vue3 project introduces electron communication

The formed vue3 project introduces electron communication

1.
After installing electron with cnpm i electron --save-dev, you need to use the ipcRenderer module in electron. When calling, using require to introduce electron will report an error, fs.existsSync is not a function or Uncaught ReferenceError: require is not defined error
. The display is caused by the introduction of the fs.existsSync statement in the node_modules/electron/index.js file.

const {
    
     ipcRenderer } = require('electron')

After checking the information, I learned that
the rendering process belongs to the browser side and does not have an integrated Node environment, so Node's basic packages like fs cannot be used.
Because there is no Node environment, the require keyword belonging to the node api cannot be used.

Electron is introduced by using window.require instead of require, because the former will not be compiled by webpack, and the require keyword in the rendering process represents the system of the node module.

vue end: js

 var renderer = window.require('electron').ipcRenderer
 renderer.send('import-study', "begin to import study")
 

electron side:

ipcMain.on('import-study',(event,message)=>{
    
    
   console.log(message)
   dialog.showOpenDialog({
    
    
    title:'选择要上传的文件',//对话框的标题
    buttonLabel: '确认', //确定按钮的自定义标签
    properties: [ 'openDirectory', 'multiSelections'], //打开文件的属性,打开文件还是文件夹,隐藏文件,多选文件
   }).then(res=>{
    
    
    if(!res.canceled){
    
    
      console.log(res.filePaths)
      event.reply('get-file-path',res.filePaths[0])
    }
   }).catch(err=>{
    
    
    console.log(err)
   });
})

vue receives electron and returns:

 renderer.on('get-file-path', (event: any, arg: string) => {
    
    
                   
                   console.log(arg)
                })

Guess you like

Origin blog.csdn.net/Stars_in_rain/article/details/132756923