2021年4月10日星期六

Electron unable to load preload.js problem

It took 3 days to set up electron & react myself. By the time I thought it was all there was a new problem

enter image description here

I want to connect electron with react. but i can't get preload.js file

If there is no preload.js file, both execution and build work fine. but After adding the preload.js file, it says that the preload.js file cannot be found (otherwise it works fine)

I tried a lot of attempts, such as changing the settings of electron's webPreferences that came out after searching, but all failed.

I don't know how to solve this problem. Thanks for telling me how to fix it. I have attached several parts of my code

The picture below is my folder structure

enter image description here

this is my electron code

// electron/main.js  import { app, BrowserWindow } from "electron";  import path from "path";    let mainWindow;  const isDev = process.env.NODE_ENV === "development";    function createWindow() {    mainWindow = new BrowserWindow({      width: 1200,      height: 800,      webPreferences: {        nodeIntegration: true,        preload: path.resolve(__dirname, "preload.js"),      },    });      if (isDev) {      mainWindow.loadURL(`http://localhost:3000`);      mainWindow.webContents.openDevTools();    } else {      mainWindow.loadFile(`${path.join(__dirname, "/index.html")}`);    }      mainWindow.on("closed", () => {      mainWindow = null;    });  }    app.on("ready", createWindow);  app.allowRendererProcessReuse = true;  

and this is my preload.js

// electron/preload.js    import { ipcRenderer } from "electron";    process.once("loaded", () => {    window.ipcRenderer = ipcRenderer;  });  

and this is my package.json enter image description here

Finally this is my webpack.electron.config.js

const path = require("path");    module.exports = {    resolve: {      extensions: [".tsx", ".ts", ".js"],    },    devtool: "source-map",    entry: "./electron/main.js",    target: "electron-main",    module: {      rules: [        {          test: /\.(js|ts|tsx)$/,          exclude: /node_modules/,          use: {            loader: "babel-loader",          },        },      ],    },    node: {      __dirname: false,    },    output: {      path: path.resolve(__dirname, "dist"),      filename: "[name].js",    },  };    
https://stackoverflow.com/questions/67041369/electron-unable-to-load-preload-js-problem April 11, 2021 at 12:06PM

没有评论:

发表评论