Search code examples
javascriptparceljs

Exported object returns undefined


I have the following singleton inside my app.js code:

const TodoManager = (function () {
    const allTodos = [];

    return {
        addNewTodo: function (title, color) {
            allTodos.push(new Todo(title, color));
        },
    };
})();

and I would like to export the addNewTodo function to another .js file, so I attached this to end of app.js:

module.exports = TodoManager

then, on my dom.js file (the file I want to use the addNewTodo function), I imported it:

import TodoManager from './app.js';

However, everytime I try to access any of its objects, it returns undefined. Am I doing something stupidly wrong?

(I am using Parcel.js as a bundler)


Solution

  • You have:

    // app.js
    require("./dom.js");
    
    const TodoManager = (function () {
      // ...
    

    You also have

    // dom.js
    import TodoManager from './app.js';
    
    const MenuBar = (function(){
      // ...
    

    This is a circular dependency. When one of the files runs, it sees that it needs to import the other, so control flow switches to the other. Then, the other sees that it needs to import the first file. But the first file is already being in the process of getting created, so it doesn't switch back. The interpreter understands you have a potential issue, but it doesn't throw an error, it tries to run the script the best it can, by setting the export of the original file to an empty object initially. But this results in bugs.

    But, in your code, app.js does not actually do anything with the require("./dom.js"); - there's no need for app.js to depend on dom.js. So, all you really need to do is remove require("./dom.js"); from app.js.