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

require (browserify) not working correctly when assigned (empty object), but works when inline

我在 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 尚未完成其导出functions/objects 并且 A 将仅在下一个价格变动时完全可用于 C,当 A 已完成导出。

这是一个例子:

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