'Electron App : Unable to load preload script

Been getting this error every time I start up my electron app.

electron/js2c/renderer_init.js:91 Unable to load preload script: C:\Users\Desktop\Projects\Electron-Apps\Electron\src\preload.js
(anonymous) @ electron/js2c/renderer_init.js:91
electron/js2c/renderer_init.js:91 Error: contextBridge API can only be used when contextIsolation is enabled

My preload.js is in the same directory as my index.js, so I'm a bit loss at debugging this. Not sure why it won't load my preload.js file. Everything was working fine up until I setup my default formatter to prettier with eslint.

Index.js

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

Preload.js

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electron', {
  notificationAPI: {
    sendNotification(message) {
      ipcRenderer.send('notify', message);
    },
  },
  filesAPI: {
    sendEmails(content) {
      ipcRenderer.send('save-delete', content);
    },
  },
});


Solution 1:[1]

As the error suggests, contextIsolation needs to be enabled to allow you to use the contextBridge API

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true, // add this
      preload: path.join(__dirname, 'preload.js'),
    },
  });

Note: contextIsolation is enabled by default starting from Electron 12.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1