Loop circular dependency: something is not a function

I recently started writing CommonJS modules, but ran into problems in the required modules. Why was storage.js unable to get the example module I need? What is the proper way to use a dependent module in this case?

EDIT: Added more information because the previous question omitted hello.js, which I thought was not causing the problem. It looks like including it throws an uncaught type error. Also, this is a piece of code for the chrome extension, and main.js is the content script.

// main.js
var hello = require('./hello');
var storage = require('./storage');
var example = require('./example');

storage.store(); 

// storage.js
var example = require('./example');
module.exports = (function() {

    function store() {example.ex();}

    return {store: store};

})();

// example.js
var storage = require('./storage');

module.exports = (function() {
    function ex() {
         console.log('example');
    }    
    return {ex: ex};    
})();

// hello.js
var example = require('./example'); // <<<< Including this gives Uncaught TypeError: example.ex is not a function
module.exports = (function() {
    function hello() {
        console.log('hello');
    }

    return {hello:hello};
})();

      

+3


source to share


1 answer


Not a direct answer to your question, but Browserify will include a self-starting feature for you. You can simplify your lib files:

// main.js
var storage = require('./storage');
storage.store();

      

Since you don't use hello

or example

, don't require them.

// storage.js
var example = require('./example');
function store() {example.ex();}
module.exports.store = store;

      

There is no need for self-starting function.

// example.js
module.exports.ex = ex;
function ex() {
    console.log('Example');
}

      



It doesn't use storage

, so don't include it.

hello.js

does not cause anything, but it causes a circular dependency, removes it.


In your updated code, you have a circular dependency between storage.js

and example.js

. Since you are not using anything from storage

in example

, you can simply remove this requirement. I still think you should remove the self-triggered functions as this is already part of commonjs.

When a module is loaded, Commonjs will run the file only once. Everything in is module.exports

then cached for future calls. The first time you enable the looping dependency, the module loader sees that it is currently being loaded and you will not get any results. Subsequent calls will end as usual.

+2


source







All Articles