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 environment but not when I go live. Here is the example:
In the html file the js files would be optionally loaded (pseudo code):
//index.cshtml
...
<script src="/Scripts/lib/require.js"></script>
<script src="/Scripts/app/service_user.js"></script>
<script src="/Scripts/app/real_service.js"></script>
#if DEBUG
<script src="/Scripts/app/mock_service.js"></script>
#endif
In the above both real_service and mock_service must be loaded in the debug version.
Each module would be defined using requirejs, eg:
//mock_service.js
define('mock_service', [],
function () {
...
});
//real_service.js
define('real_service', [],
function () {
...
});
Then when using the service I'd like to check if the mock_service has been defined:
//service_user.js
define(['require', 'real_service'],
function (require, real_service) {
if (require.isDefined('mock_service')) { // 'isDefined' is what I wish was available
var mock = require('mock_service');
mock.init(real_service);
}
...
});
So my notional 'isDefined' function would just check for a module with the given name (or names?) having been defined. Then in my code, if it is defined I can require it and use it. If not, then that is fine too.
The important thing for me is that no attempt is made to load the optional module. I could try/catch around the require statement but that would cause an attempt to load it from the server and I don't want that.
Another option would be to have a stub define that I always load and so there is always a mock to require which I can then interrogate as to whether it is the real one or not but that seems wasteful too.
Is there any one out there that is deeply in to require.js that has found that they need this functionality and have worked out a strategy for implementation?
Thank you in advance, Rob