【问题标题】:browserify circular dependency: something is not a functionbrowserify 循环依赖:某些东西不是函数
【发布时间】:2015-07-04 10:43:46
【问题描述】:

我最近开始编写 CommonJS 模块,但在需要模块时遇到了问题。为什么 storage.js 无法访问我需要的示例模块?在这种情况下需要依赖模块的正确方法是什么?

编辑:包含更多信息,因为上一个问题省略了 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};
})();

【问题讨论】:

  • var storage 是否在全局范围内?
  • 按原样粘贴代码(仅插入函数控制台输出以检查调用的内容),一切正常,没有任何错误
  • 与@dajnz 相同。你的 package.json 或 dotfiles 中是否有任何 browserify 或 webpack 覆盖?
  • 对于 browserify,我只进行了转换 - browserify-shim,没有别的

标签: javascript google-chrome-extension browserify commonjs


【解决方案1】:

不是直接回答您的问题,但 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 中没有使用来自storage 的任何内容,所以您可以删除该要求。我仍然认为您应该删除自调用函数,因为这已经是 commonjs 的一部分。

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

【讨论】:

  • 代码已更新。之前遗漏了一些重要信息
猜你喜欢
  • 1970-01-01
  • 2015-05-21
  • 2016-05-02
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 2015-01-25
  • 2011-10-28
相关资源
最近更新 更多