javascript - Webpack import returns undefined, depending on the order of imports -
i'm using webpack + babel. have 3 modules looking this:
// a.js // other imports here console.log('a'); export default 'some-const'; // b.js import someconst './a'; console.log('b', someconst); export default 'something-else'; // main.js import someconst './a'; import somethingelse './b'; console.log('main', someconst);
when main.js
executed, see following:
b undefined main some-const
if swap imports in main.js
, b
becoming first, get:
a b some-const main some-const
how come b.js
gets undefined
instead of module in first version? what's wrong?
after full workday of narrowing down issue (aka hair-pulling), i've came realize have circular dependency.
where says // other imports here
, a
imports module c
, which, in turn, imports b
. a
gets imported first in main.js
, b
ends being last link in "circle", , webpack (or commonjs-like environment, matter, node) short-circuits returning a
's module.exports
, still undefined
. eventually, becomes equal some-const
, synchronous code in b
ends dealing undefined
instead.
eliminating circular dependency, moving out code c
depends on out of b
, has resolved issue. wish webpack somehow warn me this.
edit: on last note, pointed out @cookie, there's plugin circular dependency detection, if you'd avoid hitting problem [again].
Comments
Post a Comment