Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour of require() in electron when using relative paths

I would appreciate some clarification on the following matter:

I am starting to learn electron and wanted to setup a small example to test requiring-mechanism.

Folder structure as follows:

main.js
node_modules
html
 |-index.html
[...]
js
 |-test.js
 |-test2.js

test2.js contains just one function that I export.

Now from what I read online, require(...) should resolve relative paths, but if in test.js (which is used in index.html) I use:

const aTest = require('./test2.js');

produces a module not found, while:

const aTest = require('../js/test2.js');

works just fine, which I find quite counterintuitive and from reading on SO and other sites, I thought first version should work as well. Further testing (with nested folders) indicated that the path is relative to node_modules.

--|EDIT(add): Further testing made me assume that the path is rather set relative to the html directory. For example:

console.log(__dirname)

in test.js prints the path to the html directory.|--

Why does it behave that way? Did I make a setup mistake?

(PS: I found several posts providing information about avoiding ../../../someModule, but as far as I understood all were assuming "pathing" relative to the requiring file, so that didn't help me resolve my problem.)

like image 921
Wolfone Avatar asked Nov 25 '25 12:11

Wolfone


1 Answers

Indeed, require(...) can resolve relative paths, but from a file which has itself been required.

You're indicating that test.js is used in index.html, and the module not found error message you get suggests that it is included using the src attribute of the <script> tag:

<script src="../js/test.js"></script>

Try using a require() statement instead:

<script>require('../js/test.js');</script>

then the code inside test.js should work properly:

const aTest = require('./test2.js');
// aTest();

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!