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

133 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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')
})