Note that there are some explanatory texts on larger screens.

plurals
  1. POWith requirejs is it possible to check if a module is defined without attempting to load it?
    primarykey
    data
    text
    <p>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:</p> <p>In the html file the js files would be optionally loaded (pseudo code):</p> <pre><code>//index.cshtml ... &lt;script src="/Scripts/lib/require.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/app/service_user.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/app/real_service.js"&gt;&lt;/script&gt; #if DEBUG &lt;script src="/Scripts/app/mock_service.js"&gt;&lt;/script&gt; #endif </code></pre> <p>In the above both real_service and mock_service must be loaded in the debug version.</p> <p>Each module would be defined using requirejs, eg:</p> <pre><code>//mock_service.js define('mock_service', [], function () { ... }); //real_service.js define('real_service', [], function () { ... }); </code></pre> <p>Then when using the service I'd like to check if the mock_service has been defined:</p> <pre><code>//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); } ... }); </code></pre> <p>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.</p> <p>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.</p> <p>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.</p> <p>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?</p> <p>Thank you in advance, Rob</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload