0

I'm discovering Electron and I'm facing a problem: I can't implement my "common.js" file in my "test.js" script.

Here is the architecture of my project:

rootProject
   -features(folder)
      -common.js
      -test.js
   -index.html

common.js

const hello = "hello";
module.exports = { hello };

test.js

const {hello} = require("./common.js");
console.log(hello);

index.html

<body>
  <h1>Hello World!</h1>
  <div class="flex-container">
    <span id="timeAfterRefreshGasFees"></span>
    <span id="rapid"></span>
    <span id="fast"></span>
    <span id="standard"></span>
    <span id="slow"></span>
  </div>
  <!-- You can also require other files to run in this process -->
  <script src="./renderer.js"></script>

  <!-- <script src="./features/common.js"></script> -->
  <script src="./features/test.js"></script>
</body>

In this case, I got: Error: Cannot find module './common.js'

And if I uncomment <script in index.html, I got this error: Identifier 'hello' has already been declared

I want to have a common.js file where I can put stuff inside (like const etc...)

How can I fix it?

I already tried all these solution: Getting Unexpected Token Export

Thank you!

EDIT after first solution:

I added these lines to get nodeIntegration

webPreferences: {
  nodeIntegration: true,
  contextIsolation: false,
  preload: path.join(__dirname, 'preload.js')
}

And removed <script in common.js

<script  src="./features/common.js"></script>

But now, I have this error when I'm trying to require in test.js: Cannot find module './common.js'

Naografix
  • 847
  • 2
  • 15
  • 35

2 Answers2

1

The problem is with the require() not existing in the client-side javacript

An answer more developed: https://stackoverflow.com/a/19059825/11224089

1

Like @brunocordioli072 said require is only a Node.js function, and by default Node.js functions are disabled in Electron.

Because this is Javascript you can use <script> tags like you're doing to include files.

And if I uncomment <script in index.html, I got this error: Identifier 'hello' has already been declared

This is because hello is already defined in common.js and because your including common.js with a <script> tag you can already use it inside test.js without using require.


Side note:

If you really need to use require or other Node.js functions you can simply turn on nodeIntegration and turn off contextIsolation in your BrowserWindow settings like this:

new BrowserWindow({
    webPreferences:  {
        nodeIntegration:  true,
        contextIsolation: false
    },
});

However this will create security problems in your app.

Joshua
  • 5,032
  • 2
  • 29
  • 45
  • Ok! Thank you for your answer. I understood I can call a function/var without his class if I'm using – Naografix Jun 09 '21 at 14:39
  • If you turn on `nodeIntegration` like you've done you can use `require` to import NPM modules, but not files, so `require('./common.js')` still won't work. So add your ` – Joshua Jun 09 '21 at 21:21