Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't require custom module from renderer in Electron

I'm trying to make some classes that I can import for use in my project, but I'm having some trouble actually importing the modules I'm making.

My File Structure looks like this:

├╴main.js
└╴src/
   ├╴html/
   │  └╴index.html
   ├╴css/
   │  └╴index.css
   └╴js/
      ├╴index.js
      └╴participant.js

All the index.* files are related to each other, hence having the same name.

The trouble-makers in question are index.js, my renderer for index.html, and participant.js

Here's the code I got:

// index.js
const {Participant} = require("./participant");

const addNodeBtn = document.getElementById('add-node');

addNodeBtn.addEventListener('click', () => {
  // this is really just filler code to see if everything works
  let p = new Participant("Jason");
  alert(`His name was ${p.name}`);
});

and

// participant.js
"use strict";

var Participant = class {
  constructor(name) {
    this.name = name;
  }
}

module.exports.Participant = Participant;

For whatever reason I keep getting the error "cannot find module ./participant".

Here's the alternatives I've tried:

require("participant");
require("./participant.js");
module.exports = Participant;
module.exports.Participant = class { ... }

All to no avail, all give me the same error. I've even renamed index.js to something else, thinking it was clashing with the require mechanism. Still no change.

Any help on fixing this?

UPDATE It seems to be working from within my main.js file.

like image 923
Electric Coffee Avatar asked Dec 23 '16 21:12

Electric Coffee


1 Answers

Well, turns out index.js once included through a script tag resolves its current location to the location of the including HTML code. As such, to require participant.js, given your folder structure, you will have to use require('../js/participant.js'). This only affects scripts included in HTML pages using the <script> tag. All other require's will work as expected.

like image 181
Archy Avatar answered Nov 05 '22 19:11

Archy