I'm working the first time with the combination Svelte and Electron and got some trouble in understanding the following behavior about the preload.mjs
and ES-Module/CommonJS.
My project is configured with "type"="module" in package.json
- which means I have to use import-statements instead of require (as far as I understood).
So following preload.mjs
did I build (and it worked without any errors in the DevTools until today):
import { contextBridge, ipcRenderer } from "electron";
contextBridge.exposeInMainWorld('electron', {
prisma: {
addRecord: async (data) => {
return ipcRenderer.invoke('prisma:add-record', data);
},
getAll: async () => {
return ipcRenderer.invoke('prisma:get-all');
},
}
});
Now I tried to add a new function like that:
import { contextBridge, ipcRenderer } from "electron";
contextBridge.exposeInMainWorld('electron', {
prisma: {
addRecord: async (data) => {
return ipcRenderer.invoke('prisma:add-record', data);
},
getAll: async () => {
return ipcRenderer.invoke('prisma:get-all');
},
},
export: {
export_csv: async(file_name, content) => {
return ipcRenderer.invoke('export:save-csv', {file_name, content});
},
},
});
But now nothing works anymore... I just get error messages like:
Unable to load preload script: /home/.../frontend/electron/preload.mjs
SyntaxError: Cannot use import statement outside a module
at runPreloadScript (VM214 sandbox_bundle:2:151981)
at VM214 sandbox_bundle:2:152300
at VM214 sandbox_bundle:2:152455
at ___electron_webpack_init__ (VM214 sandbox_bundle:2:152459)
at VM214 sandbox_bundle:2:152582
After searching a lot in my code and google I just tried to change the import to
const {ipcRenderer} = require('electron/renderer')
const {contextBridge} = require('electron')
And now: all errors are gone away and the app just worked as before. I do not really understand what happens here and why.
Anyone here who can explain this to me? I really want to now what happened and what I did wrong.