Search code examples
javascriptreactjsnext.jsimportcontroller

I'm having problems trying to instantiate a class (controller) in nextjs 13


I have a application in nextjs that will instantiate a class (controller) that will do all the access type, like get data from database. But always getting this error:

Error [ReferenceError]: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization

My controllers are like Object (will have methods for this type of data) that extend BusinessObject (will have methods to commit, delete, load data) that instantiate DataAccessObject inside its constructor (will have methods to access and update database). This works fine in my CRA application, but in NextJs when importing these controllers I get errors, but when I use the database directly it doesn't happen (like mongodb FindOne()).

Code that triggers error (/api/[...]/ GET method):

import MyObject from "@monorepo/controllers/MyObject";

Getting errors from any object of that type.


Solution

  • Got time to answer the second question: Why does this error only happens now that I am using a NextJs application to import the same classes, and it works fine in a classic CRA application>

    After searching through the documentation and Github Issue#32360, I believed that it is because Next.js has limited support for circular dependencies, and sometimes it might break with different versions.

    In fact, circular dependencies has always been a messy thing for JavaScript, and this statement is also supported by webpack's documentation:

    JavaScript is taking over the world as a language, as a platform and as a way to rapidly develop and create fast applications.

    But there is no browser support for CommonJS. There are no live bindings. There are problems with circular references. Synchronous module resolution and loading is slow. While CommonJS was a great solution for Node.js projects, browsers didn't support modules, so bundlers and tools like Browserify, RequireJS and SystemJS were created, allowing us to write CommonJS modules that run in a browser.

    If that does not explain enough, even Node.js (Webpack runs on Node.js) has limited tolerability for circular dependencies.

    Perhaps if you use require() instead of import(), the problem could have solved. However, the price is that it sacrifice loading a module completely before initial import - which could lead to unexpected behaviours and results.

    Conclusion: Avoid circular dependencies as much as possible.