我最近一直在使用ExtendScript Toolkit上的commonjs实现,而我仍然坚持这种“依赖循环”的事情。我的代码通过了大多数commonjs一致性测试,除了这些测试:cyclic,determinism,exactExports,monkeys。
维基说:
如果存在依赖循环,则外部模块在其传递依赖性之一需要时可能尚未完成执行;在这种情况下,“require”返回的对象必须至少包含外部模块在调用require之前准备的导出,这导致当前模块的执行。
有人可以进一步向我解释如何实施该规范吗?如果它检测到依赖循环,我会抛出异常吗?
您可以在https://github.com/madevelopers/estk
查看我的代码仅在ExtendScript Toolkit CS6上测试
答案 0 :(得分:2)
在CommonJS中,您将要导出的内容附加到导出对象上。规范的目的是,如果在文件中有一个'require'语句然后部分通过该文件,则需要原始文件,然后第二个require获取exports对象的状态,因为它就在那时。我将提供一个例子。
// file A.js
exports.A1 = {};
exports.A2 = {};
// The object returned from this require call has B1, B2 and B3
var B = require('./B.js');
exports.A3 = B.B1;
在文件B.js中:
// fie B.js
exports.B1 = {};
exports.B2 = {};
// This require call causes a cycle. The object returned has only A1 and A2.
// A3 will be added to the exports object later, *after* this file is loaded.
var A = require('./A.js');
exports.B3 = A.A1;
即使代码中有一个循环,此示例也能正常工作。这是另一个可行的例子,即使它是循环的:
var OtherModule = require('./OtherModule.js');
// even if OtherModule requires this file and causes a circular dependency
// this will work, since doAThing is only defined and not called by requiring this
// this file. By the time doAThing is called, OtherModule will have finished
// loading.
exports.doAThing = function() {
return OtherModule.doSomething() + 3;
}
即使在执行此文件代码并且定义了doAThing时不存在OtherModule.doSomething,只要doAThing直到稍后才被调用,那么一切都很好。