Javascript Webpack 导入返回 undefined,取决于导入的顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35240716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:27:50  来源:igfitidea点击:

Webpack import returns undefined, depending on the order of imports

javascriptwebpackbabeljs

提问by Alec Mev

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

我正在使用 webpack + babel。我有三个看起来像这样的模块:

// A.js

// some other imports here
console.log('A');
export default 'some-const';

// B.js

import someConst from './A';
console.log('B', someConst);
export default 'something-else';

// main.js

import someConst from './A';
import somethingElse from './B';
console.log('main', someConst);

When main.jsis executed, I see the following:

main.js被执行时,我看到以下内容:

B undefined
A
main some-const

If I swap the imports in main.js, Bbecoming the first, I get:

如果我交换 中的进口main.jsB成为第一个,我得到:

A
B some-const
main some-const

How come B.jsgets undefinedinstead of a module in the first version? What's wrong?

为什么在第一个版本中B.js得到undefined而不是模块?怎么了?

回答by Alec Mev

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, Aimports another module C, which, in turn, imports B. Agets imported first in main.js, so Bends 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 Bends up dealing with undefinedinstead.

它说// some other imports hereA导入另一个模块C,而后者又导入B. A首先在 中导入main.js,因此B最终成为“圆圈”中的最后一个链接,而 Webpack(或任何类似 CommonJS 的环境,就此而言,例如 Node)只是通过返回A's 来短路它module.exports,它仍然是undefined. 最终,它变成等于some-const,但B最终处理的是同步代码undefined

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

通过移出C依赖于 out of的代码,消除循环依赖B已经解决了这个问题。希望 Webpack 会以某种方式警告我这一点。

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].

编辑:最后一点,正如@cookie 所指出的,有一个用于循环依赖检测的插件,如果你想避免再次遇到这个问题。