Javascript Electron应用程序:无法加载预加载脚本

Javascript Electron应用程序:无法加载预加载脚本,javascript,electron,Javascript,Electron,每次我启动electron应用程序时都会遇到这个错误 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: conte

每次我启动electron应用程序时都会遇到这个错误

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
我的preload.js和index.js在同一个目录中,所以我在调试时有点不知所措。不知道为什么它不会加载我的preload.js文件。在我使用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);
    },
  },
});

如错误所示,需要启用
contextIsolation
,以允许您使用
contextBridge
API

const createWindow=()=>{
//创建浏览器窗口。
const main window=新浏览器窗口({
宽度:800,
身高:600,
网络首选项:{
上下文隔离:是的,
preload:path.join(uu dirname,'preload.js'),
},
});
注意:
contextIsolation
从Electron 12.0开始默认启用