网站搜索

typescript - 在使用 quasar 的 electron 应用中修复 Cannot read properties of undefined 错误


我目前正在使用 quasar-cli 配置和 electron 开发一个小应用程序。

我的 electron-preload.ts 看起来是这样的:

import { contextBridge} from 'electron'
import alasql from 'alasql'

contextBridge.exposeInMainWorld('Electron', {
  importdata: () => importCsv()
})

export function importCsv () {
  console.log('we get here')
  return alasql.promise('SELECT * FROM CSV("/Users/niki/example_data.csv", {headers:true, seperators:","})')
    .then(function (data) {
      return data
    })

在我的 MainLayout.vue 中,我是这样调用它的:

const firstimport = window.electronApi.importdata()

然后我继续使用这个 promise 进行一些进一步的操作,但都收到 cannot read properties of undefined 错误。我在 vscode 中也收到 .electronApi 不存在的错误。完全相同的操作在我的 electron 应用中可以正常工作,而我的那个应用不是用 quasar-cli 创建的,所以我不确定我哪里做错了。

另外,我的窗口是这样创建的,如果这有关系的话:

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    icon: path.resolve(__dirname, 'icons/icon.png'), // tray icon
    width: 1000,
    height: 600,
    useContentSize: true,
    webPreferences: {
      contextIsolation: true,
      sandbox: false,
      // More info: https://v2.quasar.dev/quasar-cli-vite/developing-electron-apps/electron-preload-script
      preload: path.resolve(__dirname, process.env.QUASAR_ELECTRON_PRELOAD)
    }
  })

  mainWindow.loadURL(process.env.APP_URL)

  if (process.env.DEBUGGING) {
    // if on DEV or Production with debug enabled
    mainWindow.webContents.openDevTools()
  } else {
    // we're on production; no access to devtools pls
    mainWindow.webContents.on('devtools-opened', () => {
      mainWindow?.webContents.closeDevTools()
    })
  }

  mainWindow.on('closed', () => {
    mainWindow = undefined
  })
}

答案#1

好的,在整晚被这些事情弄得无法入睡,并查看了不同的项目和我以前使用的旧模板后,我找到了我的错误。首先,我在调用 electronAPI 时有一个拼写错误。其次,为了让 vscode 中的语法错误消失,我需要以下文件:

我的 src 文件夹(renderer 文件夹)中的 global.d.ts

import alasql from 'alasql'

/**
 * Should match main/preload.ts for typescript support in renderer
 */
export default interface electronAPI {
  sendMessage: (message: string) => void
  importdata: () => any
}

declare global {
  interface Window {
    electronAPI: ElectronAPI,
  }

}