RequireJs使用上下文时忽略配置

时间:2017-06-16 21:26:42

标签: javascript requirejs

这就是我的页面的样子

<script>
// set the configuration for require.js syncronously
var require = {
    context: 'default',
    baseUrl: '/scripts',
    bundles: {
            'bundles/main': ['utils']
    }
};
</script>


<script src='/scripts/libs/require.js'></script>

<script>
// this throws an error because it tries to load module1.js from the current relative path instead of /scripts/module1.js
require(['module1'],function(module1){
    module1.test();
});
</script>

我已经在stackoverflow上回顾了几个类似的问题,例如这个答案:Require JS is ignoring my config

以及此处的文档:https://github.com/requirejs/requirejs/wiki/Patterns-for-separating-config-from-the-main-module

如果我正确理解这一点,通过在包含require脚本之前同步声明要求,设置应该在它加载module1时可用,但它似乎不起作用。

我最初尝试这种方式的结果相同:

 <script src='/scripts/libs/require.js'></script>

 <script>
 require.config({
    context: 'default',
    baseUrl: '/scripts',
    bundles: {
        'bundles/main': ['utils']
    }
 });
 </script>

编辑:显然当我删除上下文行时,它正常工作。我不知道为什么会破坏它。

1 个答案:

答案 0 :(得分:1)

The problem is that you are issuing a require call in a context different from the context you are using in your configuration. The default name for a context if you do not specify it is _ (not default). With the code you show, the context in your configuration is default. But you use the default require call provided by RequireJS, which operates in the context named _.

When you specify a context name different from the default, you want to save the return value from the require.config call, and the use that value instead of the default require:

var myReq = require.config({
    context: 'default',
    baseUrl: '/scripts',
    bundles: {
        'bundles/main': ['utils']
    }
});

myReq(['module1'],function(module1){
    module1.test();
});

See here for the documentation regarding how to use context.

If you do not actually need to use a context, then the easiest solution is to just remove context: 'default' from your configuration.