2015-07-04 78 views
3

我最近开始编写CommonJS模块,但面临需要模块的问题。为什么storage.js无法访问我所需的示例模块?在这种情况下需要依赖模块的正确方法是什么?browserify循环依赖:有些东西不是函数

编辑:包括更多的信息,因为前面的问题省略了hello.js,我认为这不是问题的原因。似乎包括它会导致未捕获的类型错误。此外,这是Chrome扩展的代码的一部分,main.js是内容脚本。

// main.js 
var hello = require('./hello'); 
var storage = require('./storage'); 
var example = require('./example'); 

storage.store(); 

// storage.js 
var example = require('./example'); 
module.exports = (function() { 

    function store() {example.ex();} 

    return {store: store}; 

})(); 

// example.js 
var storage = require('./storage'); 

module.exports = (function() { 
    function ex() { 
     console.log('example'); 
    }  
    return {ex: ex};  
})(); 

// hello.js 
var example = require('./example'); // <<<< Including this gives Uncaught TypeError: example.ex is not a function 
module.exports = (function() { 
    function hello() { 
     console.log('hello'); 
    } 

    return {hello:hello}; 
})(); 
+0

var storage是否在全局范围内? – Philipp

+0

刚刚粘贴你的代码(只在功能控制台输出中插入以检查所谓的内容),并且一切正常,没有任何错误 – dajnz

+0

与@dajnz相同。你有没有在你的package.json或点文件中的任何browserify或webpack覆盖? –

回答

2

不是直接回答你的问题,但Browserify将在自调用函数包为您服务。您可以简化您的LIB文件:

// main.js 
var storage = require('./storage'); 
storage.store(); 

因为你不使用helloexample,并不需要他们。

// storage.js 
var example = require('./example'); 
function store() {example.ex();} 
module.exports.store = store; 

不需要在这里通过自我调用功能。

// example.js 
module.exports.ex = ex; 
function ex() { 
    console.log('Example'); 
} 

这不使用storage,所以不要包括它。

hello.js什么都不做,只是触发循环依赖,将其删除。


在你更新的代码,你有storage.jsexample.js之间的循环依赖。因为您不使用中example中的任何内容,您可以删除那些需要的内容。我仍然认为你应该删除自我调用函数,因为这已经是commonjs的一部分。

加载模块时,Commonjs将只执行一次该文件。然后将module.exports上的所有内容缓存起来以备将来调用。当您第一次包含循环依赖项时,模块加载程序会发现它当前正在加载,并且没有得到任何结果。后续的通话将照常完成。

+0

代码更新。以前忽略了一些重要的信息 –