Webpack import returns undefined, depending on the order of imports

后端 未结 1 1903
予麋鹿
予麋鹿 2021-01-29 23:39

I\'m using webpack + babel. I have three modules looking like this:

// A.js

// some other imports here
console.log(\'A\')         


        
1条回答
  •  离开以前
    2021-01-29 23:48

    After almost a full workday of narrowing down the issue (AKA hair-pulling), I've finally came to realize that I have a circular dependency.

    Where it says // some other imports here, A imports another module C, which, in turn, imports B. A gets imported first in main.js, so B ends up being the last link in the "circle", and Webpack (or any CommonJS-like environment, for that matter, like Node) just short-circuits it by returning A's module.exports, which is still undefined. Eventually, it becomes equal to some-const, but the synchronous code in B ends up dealing with undefined instead.

    Eliminating the circular dependency, by moving out the code that C depends on out of B, has resolved the issue. Wish Webpack would somehow warn me about this.

    Edit: On the last note, as pointed out by @cookie, there's a plugin for circular dependency detection, if you'd like to avoid hitting this problem [again].

    0 讨论(0)
提交回复
热议问题