With requirejs is it possible to check if a module is defined without attempting to load it?

后端 未结 2 1271
清歌不尽
清歌不尽 2020-12-13 06:40

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

相关标签:
2条回答
  • 2020-12-13 06:46

    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.

    0 讨论(0)
  • 2020-12-13 06:54

    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");
    
    0 讨论(0)
提交回复
热议问题