1

I am working on a project in JavaScript where I am writing my code in separate files using the revealing module pattern.

I am also utilizing Gulp to concat those files together into one app.js file.

The issue I am having is when I am trying to use one module within another. Please take a look at my example code below:

My app.js file looks similar to this:

const componentOne = (function(){ ... return { myMethod: myMethod} })();
const componentTwo = (function(){ ... return { myMethod: myMethod} })();
const componentThree = (function(){ ... return { myMethod: myMethod} })();

In the individual component files, I can call componentOne.myMethod() from componentTwo and it works as expected.

However, the problem I have is when I want to call componentThree.myMethod() from within componentTwo. The error that I get is componentThree is undefined. However, when I manually modify the compiled app.js to move the componentThree code block to be above componentTwo, it works fine.

I would like to understand why this is, and if there is any way around it without using something like Browserify. Or is Browserify (or webpack, requirejs, etc.) a good solution to fix an issue like this?

cjh193
  • 309
  • 2
  • 3
  • 9
  • 1
    Well, it depends on *when* you are trying to call the method. If you are calling it during the initializarion of `componentTwo` then that can't work of course, because `componentThree` is not initialized yet. If that's the case, all you can do is rearrange them so that they are initialized in the necessary order. – Felix Kling Sep 10 '17 at 15:45
  • I understand that I need to rearrange them in the proper order, however my code is being concatenated automatically as of now just by the individual files. Is there something I can do, maybe create an entry file such as main.js, and set it up like this: const app = app || {}; Then I can add my components to it and when I compile it will compile in that order? Not sure how to do it exactly though... – cjh193 Sep 10 '17 at 15:47
  • 1
    You should be able to control the order in which files are concatenated. Using actual modules and something like browserify would certainly be better though. – Felix Kling Sep 10 '17 at 15:49
  • Could it be that you are missing `()` after each function in your example? I assume the functions get executed immedialty. – Felix Kling Sep 10 '17 at 15:50
  • Not missing the (), just didn't include it in the example code. Yes, they are immediately invoked functions. Updated my example code. – cjh193 Sep 10 '17 at 15:51
  • That's what I meant ;) – Felix Kling Sep 10 '17 at 15:53

0 Answers0