3

I want to achieve the following setup:

// app.js
(function () {
    const add = function() {
        // add
    }
    const substract = function() {
        // substract
    }

     require('./module1');
     require('./module2');  
})()


// module1.js
add();
substract();

The problem is that when the functions are called from within the module1.js, they are undefined (all this is bundled with webpack).

I know the solution of "exporting" and "importing" between the various modules/files. I am just wondering if I can I achieve this setup in order to avoid imports in the many modules that I use (imagine, for example, having to import them to 50 modules/files).

What is the proper way to achieve this setup (if possible)?

Thanx in advance.

Vagelis Prokopiou
  • 2,285
  • 19
  • 14
  • Only thing you need to worry about is your path for requiring module1 and 2. If they are imported correctly, everything will work just fine – binariedMe Jun 12 '17 at 09:14
  • 1
    If you want to use these functions in Module 1, shouldn't you be doing this the other way around? – Niels Jun 12 '17 at 09:15
  • 1
    @binariedMe no, it won't work. The variables `add` and `subtract` are only available within the _lexical_ scope of that closure, and not exposed to any module that is `require`d therein. – Alnitak Jun 12 '17 at 09:15
  • @Alnitak yeah, you're right. Apologies for wrong information. :( – binariedMe Jun 12 '17 at 09:26

3 Answers3

0

Try this if you can:

// app.js

(function addSubst() {
    const add = function() {
        // add
    }
    const substract = function() {
        // substract
    }

     require('./module1');
     require('./module2');  
})()

// module1.js

import {addSubst} from 'app';//app.js
add();
substract();

better explanation and for more languajes here

Foo Bar
  • 165
  • 2
  • 14
0

The scope of the IIFE function ends after it call it self and the inside add ,substract , they will have not refrence after the IIFE you should try to export both varibles from this file . If you try to apply the clousure

function currentModule() {
    const add = function() {
        // add
    }
    const substract = function() {
        // substract
    }
 return { add : add, substract : substract}
})
var instanceHere = currentModule();
instanceHere.Add();
user 13
  • 134
  • 8
0

The way I managed to achieve this, was to create a global object (namespace) for my app.

(function() {
    APP = window.APP || {};

    APP.add = function() {
        console.log('Adding...');
    }
    APP.substract = function() {
        console.log('Substracting...');
    }

    // Import the modules.
    require('./module1');
    require('./module2');
})();

// module1.js
APP.add();        // Outputs "Adding..."
APP.substract();  // Outputs "Substracting..."
Vagelis Prokopiou
  • 2,285
  • 19
  • 14