Require JS is ignoring my config

前端 未结 2 451
春和景丽
春和景丽 2020-12-09 18:07

I\'m having pretty simple directory structure for scripts:

/js/        <-- located in site root
    libs/
        jquery-1.10.1.min.js
        knockout-2.         


        
相关标签:
2条回答
  • 2020-12-09 18:46

    Fixed the issue.

    My config was being loaded asynchronously, and therefore the config paths weren't set before my require statement was being called.

    As per the RequireJS docs Link here, I added a script call to my config before the require.js call. And removed the data-main attribute.

    var require = {
        baseUrl: '/js',
        paths: {
            'jquery':      'vendor/jquery/jquery-2.0.3.min',
            'picker':      'vendor/pickadate/picker.min',
            'pickadate':   'vendor/pickadate/picker.date.min'
        },
        shim: {
            'jquery': {
                exports: '$'
            },
            'picker':    ['jquery'],
            'pickadate': {
                deps:    ['jquery', 'picker'],
                exports: 'DatePicker'
            }
        }
    }
    

    All is now working

    0 讨论(0)
  • 2020-12-09 18:48

    Solved.

    The problem was that config file defined in data-main attribute is loaded asynchronously just like other dependencies. So my config.js accidentally was never completely loaded and executed before require call.

    The solution is described in official RequireJS API: http://requirejs.org/docs/api.html#config

    ... Also, you can define the config object as the global variable require before require.js is loaded, and have the values applied automatically.

    So I've just changed my config.js to define global require hash with proper configuration:

    var require = {
        baseUrl: "/js/libs",
        paths: {
            "jquery":       "jquery-1.10.1.min",
            "knockout":     "knockout-2.2.1",
            "komapping":    "knockout.mapping"
        }
    };
    

    and included it just BEFORE require.js:

    <script type="text/javascript" src="/js/config.js"></script>
    <script type="text/javascript" src="/js/require.js"></script>
    

    This approach allows to control script execution order, so config.js will always be loaded before next require calls.

    All works perfectly now.

    0 讨论(0)
提交回复
热议问题