I want to be able to optionally define a module and then use it or not in my code. The particular situation I\'m considering is loading mock/stub modules in the debug/test
Although David Wolf's answer was close to the mark it didn't fully meet my needs.
The problem is that require asynchronously resolves requirements so in the in the example I gave and using David's suggestion require.defined('mock_service')
will return false
because although it has been specified it has not yet been resolved.
When investigating this I did find another function specified
. In the example require.specified('mock_service')
will return true
but then trying to get a reference using require('mock_service')
fails because it hasn't yet been resolved.
That, fortunately, is easily fixed by using the callback version of require. Putting it all together we have:
if (require.specified('mock_service')) {
require( [ 'mock_service' ], function (mock) {
mock.init(real_service);
});
}
@David Wolf - thanks, would not have got there without your help.
I was just looking for this myself, the require global has a "defined" method on it which takes a module name and returns true or false.
// returns true
require.defined("my/awesome/defined/module");
// returns false
require.defined("not/yet/loaded");