我正在构建一个模块,我希望为使用AMD的人员和不使用AMD的人员提供这两个模块。例如,我希望把它与RequireJS工作:如何给JavaScript模块提供有条件的AMD支持?
require(['Module'], function (Module) {
// do stuff with module
});
但我也希望通过手动将所有的依赖关系的工作(考虑到他们也没有AMD工作)。
如何测试此行为是否正确?
我正在构建一个模块,我希望为使用AMD的人员和不使用AMD的人员提供这两个模块。例如,我希望把它与RequireJS工作:如何给JavaScript模块提供有条件的AMD支持?
require(['Module'], function (Module) {
// do stuff with module
});
但我也希望通过手动将所有的依赖关系的工作(考虑到他们也没有AMD工作)。
如何测试此行为是否正确?
我发现的一个工作方法是在我的脚本文件中使用模块模式,这样就没有泄漏的依赖关系。之后,我构建了一个内部函数,它接收我的依赖项作为参数,并返回表示要导出的模块的对象。
然后,我检查是否有define
函数可用,并且它是否设置了amd
属性。如果是,那么我用define来注册该模块,否则我将它作为全局导出。
下面是此代码的框架。我们假设该模块被命名为Module
,它由两所部分组成,dep1
和dep2
:
(function (exports) {
"use strict";
var createModule = function (dep1, dep2) {
var Module;
// initialize the module
return Module;
}
if (typeof define === 'function' && define.amd) {
define(['dep1', 'dep2'], function (dep1, dep2) {
return createModule(dep1, dep2);
});
} else {
exports.Module = createModule(dep1, dep2);
}
})(this);
关于测试,我目前使用的自耕农它,与mocha
和PhantomJS
。以下是如何根据需求进行测试的方法。我用来测试这两种情况(有和没有AMD)的方法是有两个单独的html测试。首先,你需要在Gruntfile添加第二页:
// headless testing through PhantomJS
mocha: {
all: ['http://localhost:3501/index.html', 'http://localhost:3501/no-amd.html']
},
在第一种情况下,有正常需要基于模板:
<script src="lib/mocha/mocha.js"></script>
<!-- assertion framework -->
<script src="lib/chai.js"></script>
<!-- here, main includes all required source dependencies,
including our module under test -->
<script data-main="scripts/main" src="scripts/vendor/require.js"></script>
<script>
mocha.setup({ui: 'bdd', ignoreLeaks: true});
expect = chai.expect;
should = chai.should();
require(['../spec/module.spec'], function() {
setTimeout(function() {
require(['../runner/mocha']);
}, 100);
});
</script>
对于测试非AMD,我们需要明确包含模块和所有依赖关系。毕竟在页面中,我们包括跑步者。
<script src="lib/mocha/mocha.js"></script>
<!-- assertion framework -->
<script src="lib/chai.js"></script>
<!-- include source files here... -->
<script src="scripts/vendor/dep1.js"></script>
<script src="scripts/vendor/dep2.js"></script>
<script src="scripts/Module.js"></script>
<script>
mocha.setup({ui: 'bdd', ignoreLeaks: true});
expect = chai.expect;
should = chai.should();
</script>
<script src="spec/romania.spec.js"></script>
<script src="runner/mocha.js"></script>
有两个不同的规格没有任何意义,但规范也应该与AMD一起工作,没有它。该解决方案与我们用于该模块的解决方案类似。
(function() {
"use strict";
var testSuite = function (Module) {
// break the module into pieces :)
};
if (typeof require === 'function') {
require(['Module'], function (Module) {
testSuite(Module);
});
} else {
// if AMD is not available, assume globals
testSuite(Module);
}
})();
如果您有不同或更优雅的方式来做到这一点,请张贴在这里作为答案。我很乐意接受更好的答案。 :)
更好的选择不是将AMD添加到代码中,而是构建两个单独的版本 - 纯JS和AMD。请阅读以了解原因:https://github.com/theironcook/Backbone.ModelBinder/issues/83 – ddotsenko