简体   繁体   English

Webpack从模块中提取依赖于外部作用域的功能

[英]Webpack extracts function, from module, that depends on outer scope

I notice this bug sometimes when there is very little code inside a function of a module: 我有时会在模块功能内部只有很少的代码时注意到此错误:

// module A
import data from "data.json";

export function getSomeData() {
    return data;
}

// module B
impoort { getSomeData } from "moduleA";

alert(getSomeData());

Then the error is something along the lines of 那么错误就是

TypeError: data_json__WEBPACK_IMPORTED_MODULE_1__ is undefined TypeError:data_json__WEBPACK_IMPORTED_MODULE_1__未定义

I notice at the top of module B there are some binding exports (whatever that is) 我注意到模块B的顶部有一些绑定输出(无论是什么)

/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSomeData", function() { return getSomeData; });

And this is making me think that whenever possible, in order to optimize things, webpack is bundling it so that only this function gets executed but it misses that it's dependent on data from the module itself. 这使我认为,只要有可能,为了优化性能,webpack会将其捆绑在一起,以便仅执行此功能,但是却错过了它依赖于模块本身的数据。 How can I prevent this from happening (other than writing better code, duh)? 我如何防止这种情况发生(除了编写更好的代码,,)?

I'm posting this for any lost souls in the future. 我会将其发布给将来任何迷失的灵魂。

I found the reason it was that I was including module B in module A as well and this appears to be a very smart way webpack handles recursive includes (where node would return an empty object). 我发现原因是我也在模块A中包括了模块B,这似乎是Webpack处理递归包含(节点将返回空对象的一种非常聪明的方式)。 Sadly for people without the proper knowledge like myself this could be pretty frustrating and time consuming to debug. 可悲的是,对于像我这样没有适当知识的人来说,这可能非常令人沮丧,并且调试起来很费时间。

Hope it helps someone. 希望它可以帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM