javascriptelectronmacos-darkmodeelectron-vue

Electron NativeTheme: Cannot set property 'themeSource' of undefined


currently I am trying to setup a system/light/dark mode switcher in my electron app. For the electron app, I have used the electron-vue library and upgraded then the electron version to 7.3.2.

So now I thought, I can use the new API nativeTheme from electron in order to create this new function. But the problem, which I now get is that nativeTheme is undefined, when I import it:

TypeError: Cannot set property 'themeSource' of undefined
    at VueComponent.theme (Settings.vue?e12e:62)
    at Watcher.run (vue.esm.js?a026:4577)
    at flushSchedulerQueue (vue.esm.js?a026:4319)
    at Array.eval (vue.esm.js?a026:1989)
    at flushCallbacks (vue.esm.js?a026:1915)

Now the code looks like this:

import { nativeTheme } from "electron";
// ...

watch: {
  theme(val) {
    localStorage.setItem("theme", val);
    nativeTheme.themeSource = val;
  }
}

I have also already tried to use the requirejs variant like

const { nativeTheme } = require("electron");

But I get the same error obviously. I already search for this topic of course here and here but both didn't resolved my issue. Is there something which I have missed?

In addition I also send here the package.json with the versions: package.json - devDependencies


Solution

  • nativeTheme is a main process module. You can't import it directly from a renderer process. You have to rely on IPC calls or Electron's remote module to use it in a renderer process.

    const { nativeTheme } = require("electron").remote;