gpt4 book ai didi

javascript - require(browserify)在分配(空对象)时无法正常工作,但在内联时可以正常工作

转载 作者:行者123 更新时间:2023-11-28 13:24:30 25 4
gpt4 key购买 nike

我在 React (coffee jsx) 中有以下组件定义:

CompUtils = require './../utils/comp-utils'

...

render: ->
console.log CompUtils # prints {} (empty object)
<div>
Then
{CompUtils.getConstructComponent @props.construct, @props.onUpdate, @props.onRemove}
</div>

但这有效:

  render: ->
console.log require('./../utils/comp-utils')
<div>
Then
{require('./../utils/comp-utils').getConstructComponent @props.construct, @props.onUpdate, @props.onRemove}
</div>

我对此感到非常困惑。请注意,CompUtils 已在其他组件中成功使用。

最佳答案

通常当你从 require 调用中得到一个空对象时,这是因为你有循环依赖。所以你需要A,它需要B,它需要C,它需要A。在这种情况下,C 将得到一个代表 A 的空对象,因为 A 尚未完成其函数/对象的导出,并且 A 仅在 A 完成导出后的下一个时间点对 C 完全可用。

这是一个例子:

// a.js
var b = require('./b');
module.exports = {
doStuff: function () {

}
}

// b.js
var c = require('./c');

// c.js
var a = require('./a');

// This will fail because a.js hasn't exported doStuff yet, since a required b, which
// required c, which required a.
a.doStuff();

您得到空对象的原因是 Browserify 在模块代码运行之前创建了一个表示该模块的 module.exports 的空对象。这意味着另一个模块可以在完成之前需要它,只是它还没有完全烘焙。

关于javascript - require(browserify)在分配(空对象)时无法正常工作,但在内联时可以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30209965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com