1

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?

ChesterWOV
  • 333
  • 2
  • 10
  • 1
    See the warning in the [official Electron documentation](https://www.electronjs.org/docs/latest/tutorial/tutorial-preload#augmenting-the-renderer-with-a-preload-script). Sandboxing could be the cause of your problem. – Alexander Leithner Jan 28 '23 at 12:54

1 Answers1

0

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')
})
ChesterWOV
  • 333
  • 2
  • 10