‘require’ is not defined in Electron v12.0.0 in renderer process

Preflight Checklist

  • I have read the Contributing Guidelines for this project.
  • I agree to follow the Code of Conduct that this project adheres to.
  • I have searched the issue tracker for an issue that matches the one I want to file, without success.

Issue Details

  • Electron Version:
    • 12.0.0
  • Operating System:
    • macOS 11.1
  • Last Known Working Electron version:
    • 11.2.1

Expected Behavior

‘require’ should import the module in the renderer process

Actual Behavior

getting undefined error: ‘Uncaught ReferenceError: require is not defined’

To Reproduce

in index.html file, just import any electron module

Screenshots

Additional Information

1 possible answer(s) on “‘require’ is not defined in Electron v12.0.0 in renderer process

  1. https://github.com/electron/electron/blob/master/docs/breaking-changes.md#default-changed-worldsafeexecutejavascript-defaults-to-true

    This is intentional and is listed in the breaking changes doc, contextIsolation now defaults to true rather than false in 12.0.0 to make renderer processes safer.

    The safer solution is to take renderer code that uses require/import and move it into a preload script, then carefully control what gets exported from the preload script & is visible to scripts running in the renderer process. For a trivial example, instead of exposing all of fs such that fs.appendFile() is callable from the renderer, you might have the preload script export a function appendToLog() that uses fs.appendFile(). This way if any hostile code is loaded over the network somehow, that hostile code would only have access to appendToLog() instead of all of fs.

    Alternatively, if you have a lot of code in place already and migration is nontrivial, you may want to explicitly set contextIsolation: false in the short term to get up and running again until migration is complete.