【问题标题】:require (browserify) not working correctly when assigned (empty object), but works when inlinerequire(browserify)在分配(空对象)时不能正常工作,但在内联时工作
【发布时间】:2015-07-24 10:53:49
【问题描述】:

我在 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已经在其他组件中成功使用了。

【问题讨论】:

  • 就像你说的那样,它应该像在其他组件中一样工作,所以它必须是特定于这个的。
  • 你能把coffeescript生成的JavaScript代码贴出来吗?

标签: javascript coffeescript reactjs browserify


【解决方案1】:

通常当你从 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 的空对象。这意味着另一个模块可以在它完成之前需要它,它只是没有完全烘焙。

【讨论】:

  • 找到循环依赖。很好的帮助!
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
  • 2015-02-14
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多