天天看點

在Electron中,渲染程序與主程序互動時,使用require報錯

在Electron中,渲染程式與主程式互動時,使用require報錯

const osenv = require('osenv');

Uncaught ReferenceError: require is not defined

在渲染程序中使用osenv擷取User目錄的時候使用require導入osenv包的時候出錯。

修改為 import { osenv } from 'osenv';依然會報錯。

兩種解決方案:

1、直接在html的script腳本中使用require導包,并使用。

2、在main.js,也就是主程序中寫上內建node的那個工具為true。

app.on('ready', () => {
  mainWindow = new BrowserWindow({
  	webPreferences: {
      nodeIntegration: true, // 是否內建 Nodejs,把之前預加載的js去了,發現也可以運作
    }
  });
  mainWindow.loadURL(`file://${app.getAppPath()}/index.html`);
  mainWindow.on('closed', () => { mainWindow = null; });
});
           

繼續閱讀