How to use with electron-store? #251
Replies: 4 comments 1 reply
-
uses |
Beta Was this translation helpful? Give feedback.
-
I added the following code in my import { ipcRenderer, contextBridge } from 'electron'
contextBridge.exposeInMainWorld('electron', {
store: () => ipcRenderer.invoke('store')
}) And added the following code in function createWindow(): void {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 900,
height: 670,
show: false,
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.ts'),
sandbox: false,
webSecurity: false,
}
})
ipcMain.handle('store', () => require('electron-store'))
...
} But using this in the .vue file will cause an error. const Store = await window.electron.store()
// caught (in promise) TypeError: Cannot read properties of undefined (reading 'store') Did i miss something? |
Beta Was this translation helpful? Give feedback.
-
Modules cannot be exposed like this, all processing should be in the main process, and you also ignore preload scripts. |
Beta Was this translation helpful? Give feedback.
-
Thank you for your hint. Now I understand that each process in Electron has its own specific role. I made these now and it works as expected. // src/preload/index.ts
contextBridge.exposeInMainWorld('store', {
get: (key: string) => ipcRenderer.invoke('electron-store-get', key),
set: (key: string, value: unknown) => ipcRenderer.invoke('electron-store-set', key, value),
}) // src/preload/index.d.ts
interface IStore {
get(key: string): Promise<any>
set(key: string, value: any): Promise<void>
}
declare global {
interface Window {
electron: ElectronAPI
api: unknown
store: IStore
}
} // src/main/index.ts
import Store from 'electron-store'
Store.initRenderer()
const store = new Store()
function createWindow(): void {
...
ipcMain.handle('electron-store-get', (_, key: string) => store.get(key))
ipcMain.handle('electron-store-set', (_, key: string, value: any) => store.set(key, value))
...
} // my-vue-file.vue
await window.store.set("foo", "bar")
const value = await window.store.get("foo")
console.log(value) // output bar Am I doing the right thing? Or is there anything I can improve? |
Beta Was this translation helpful? Give feedback.
-
I am new to electron, My project structure is electron-vite + vue3 + typescript.
Adding one of the following two lines in the .vue file will cause an error.
So, how to import electron-store?
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions