Search code examples
node.jselectronrequire

Require relative path in "client-side" JS in electron


How does require work in Electron for scripts that are executed by <script> tags in HTML files? For example, I have:

-index.html
-langs/js.js
-langs/test.js

I have <script src="langs/js.js"></script> in index.html and I want to require langs/test.js from langs/js.js, but this doesn't work:

require("./test");

It has to be require("./langs/test"); even though the relative path from js to test is just "./test". Is there a way to make it work without specifying the full path from the HTML file in every require?


Solution

  • Always use require to load CommonJS modules, if you don't then Node won't be able to set up the module scope correctly and things will break in subtle ways. If you load js.js with <script>require('./langs/js.js')</script> then require('./test') will work as you expect.