Reputation: 149
I'm new to Electron and Node. I can't seem to require()
a local .js file from another one in Electron and I don't understand the problem. I think what I'm missing is something pretty simple, but I can't find it.
Here's my file structure:
/
package-lock.json
node_modules
main.js
package.json
game/
...
test.js
properties.js
assets/html/
main_window.html
main.js
only loads main_window.html
into an Electron window and not much else.test.js
from inside the html file using <script src="../../game/test.js"></script>
.Here's test.js
:
const properties = require('./properties');
...
In return I get this error in Dev Tools console:
Uncaught Error: Cannot find module './properties'
When I use node test.js
command in the game
folder, the file gets imported, everything works just fine. But when I switch to Electron and use npm start
from root I think I'm requiring the local .js file as it should be, by putting a dot and a forward slash before its name. And despite being in the same folder as the test.js
file, it can't seem to locate properties.js
.
Also package.json
file, just in case it might be needed:
{
"name": "economy-board-game-electron",
"version": "1.0.0",
"description": "Recreation of that board game for educational purposes.",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "Edvin Boul",
"license": "MIT",
"dependencies": {
"electron": "^4.0.1"
}
}
Upvotes: 2
Views: 7112
Reputation: 2189
The path may be relative to the html file, try doing ../../game/properties, and if that works, consider putting your main html entry point on the same level as your game directory –
Electron doesn’t require files to be structured in any special way, but organizationally might be simpler to reason about it that way so you don’t have to write long backtracking paths.
It’s also how most of their examples are done, they try to make it so you can pretty much keep a typical website structure.
Upvotes: 9
Reputation: 3623
I had the same problem and asked for this about one hour ago, just got the right answer (in the comments): Issue in requiring a custom module.
<script>
tag which references test.js
from your HTML.Exports both your JS files with module.exports.Test = Test;
and module.exports.Properties = Properties;
. These instructions have to be in their respective file, and at the end. I assume that your classes (or whatever your want to export) are named Test
and Properties
.
Requires ./../../game/test
in your HTML file, between <script>
tags. (not sure about the path, but you need to start from your HTML file location)
./properties
in test.js
.Upvotes: 1