Javascript 如何在Electron中通过preload.js要求模块

Javascript 如何在Electron中通过preload.js要求模块,javascript,node.js,electron,Javascript,Node.js,Electron,我正在尝试重构一个Electron应用程序,使其更加安全,并且正在努力找出如何构造preload.js文件和渲染器文件(mainWindow.js) 给定在my main.js文件中创建的窗口,因此: const win = new BrowserWindow({ title: app.name, show: false, width, height, webPreferences: { no

我正在尝试重构一个Electron应用程序,使其更加安全,并且正在努力找出如何构造preload.js文件和渲染器文件(mainWindow.js)

给定在my main.js文件中创建的窗口,因此:

const win = new BrowserWindow({
        title: app.name,
        show: false,
        width,
        height,
        webPreferences: {
            nodeIntegration: false,
            enableRemoteModule: false,
            contextIsolation: true,
            preload: path.join(__dirname, "./js/preload.js"),
        },
    });
…还有一个preload.js,类似这样:

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

contextBridge.exposeInMainWorld("api", {
    logStuff: (arg) => ipcRenderer.invoke("logStuff", arg),
});

如何获取mainWindow.js(渲染器进程)中的代码,并将require语句移到preload.js,以便在mainWindow.js中提供必要的模块。具体来说,我使用的是必须在渲染过程中运行的Dexie IndexedDB模块

mainWindow.js

const db = require("../js/database");

...

//create db if no data exists
function setup() {
    db.transaction("rw", db.entries, function* () {
        if ((yield db.entries.count()) === 0) {
            yield db.entries.bulkPut(dlist());
        }
    }).catch((error) => {
        console.error(error.stack);
    });
}
我是否应该将此添加到preload.js

window.db = require("../js/database");
(database.js是需要Dexie并设置db模式的地方)

然后在mainWindow.js中引用窗口对象之外的模块?乙二醇

function setup() {
    window.db.transaction("rw", window.db.entries, function* () {
        if ((yield window.db.entries.count()) === 0) {
            yield window.db.entries.bulkPut(dlist());
        }
    }).catch((error) => {
        console.error(error.stack);
    });
}
或者所有的db操作都应该发生在预加载脚本中?这真的是安全方面的最佳方法吗