简体   繁体   中英

Cannot use module "dotenv" in my preload.js even if I have it in my dependencies

I have just started using Electron.

This is the start of my preload.js :

const { contextBridge } = require('electron');
require('dotenv').config();
// ...

When I used npm start , the app started normally, except that the preload.js didn't do anything. I opened the developer tools and saw this error:

Error: module not found: dotenv
    at preloadRequire (...)
...

Then I checked my npm-shrinkwrap.json :

"devDependencies": {
    // ...
    "dotenv": "^16.0.3",
    "electron": "^22.1.0"
}

Well, it sure had dotenv .

So, how can I make preload.js be able to use dotenv ?

Thanks to Alexander Leithner , I worked out the problem.

In the documentation , it says the 'sandbox' limits what I can 'require' from preload.js; so to disable it, set sandbox: false or nodeIntegration: true in webPreferences in the BrowserWindow options.

Example

app.whenReady().then(() => {
  const win = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true
    }
  })
  win.loadURL('https://google.com')
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM