-1

I have an application written in the electron module. When I add a script from a JS file to an html file or enter a script between <script> tags and define a new module, I get an error: ReferenceError: require is not defined

This is my HTML script: <script src="../scripts/computer.js"></script>

This is the javascript file: const os = require("os")

I wanted to fetch information from my computer and then display it in my application using the "os" module but it doesn't work

Maciex
  • 1
  • 1
  • maybe package.json have `module` type specified - try `import os from 'os'` – Dreamy Player Dec 02 '22 at 12:37
  • Related, if Electron doesn't add `require` (and access to things like `os`) to the render process: https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file – T.J. Crowder Dec 02 '22 at 12:40
  • Normally for getting such access to os data you should used the main process so put code inside you entry point script (main.js or index.js depending of what you put inside you package.json file). You would better have a deep look inside the Electron docs. Anyway if you want to "require" in your renderer process (your case computer.js) as require is in the node world you should declare in the webPreferences of your main Window nodeIntegration to true and contextIsolation to false. They are not advised setting for security but could be solution to start to get how the processes communicate. – Alain BUFERNE Dec 03 '22 at 18:04

2 Answers2

0

require is not native for browser, it is a part of Node.js

there is a good explanation in the answer to this post

how to use react require syntax?

nlukjanov
  • 1
  • 1
0
const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      ...
      nodeIntegration: true
      ...
    })

You can add 'nodeIntegration: true' to your window attribute in main.js