B. *_*teh 8 javascript reactjs electron
我正在使用 Electron React 和 MySQL 构建一个应用程序,我被困在预加载脚本中,我想让我的数据库实例在渲染器进程中可用,我收到以下错误错误 :找不到模块:./config/db在控制台中。当我尝试在预加载脚本中需要一个模块时,就会发生这种情况。
const { app, BrowserWindow } = require("electron");
const path = require("path");
const isDev = require("electron-is-dev");
const dotenv = require("dotenv");
//load .env
dotenv.config();
function createWindow() {
// Create the browser window.
const mainWindow = new BrowserWindow({
title: "Electron",
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
devTools: isDev,
},
});
//get url dependig on envirement (dev/prod)
const url = isDev
? `http://localhost:${process.env.PORT}/`
: `file://${path.join(__dirname, "../../dist/react/index.html")}`;
// load the url
mainWindow.loadURL(url);
// Open the DevTools.
isDev && mainWindow.webContents.openDevTools();
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow();
app.on("activate", function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
if (process.platform !== "darwin") app.quit();
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
require("./handlers");
Run Code Online (Sandbox Code Playgroud)
预载
const { contextBridge, ipcRenderer } = require("electron");
const { db } = require("./config/db");
contextBridge.exposeInMainWorld("mainApi", {
db,
});
Run Code Online (Sandbox Code Playgroud)
从 Electron v20.0.0 开始,该sandbox参数默认为true(根据Breaking Changes列表)
该属性的副作用之一sandbox是它只需要一些东西:
暴露了一个类似于 Node 的 require 模块的 require 函数,但只能导入 Electron 和 Node 内置模块的子集:Run Code Online (Sandbox Code Playgroud)electron (only renderer process modules) events timers url
要禁用沙箱,只需添加sandbox: false到您的webPreferences窗口创建中:
electron (only renderer process modules)
events
timers
url
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2284 次 |
| 最近记录: |