【问题标题】:RequireJS module load timeout when using bundles使用包时RequireJS模块加载超时
【发布时间】:2015-08-22 03:53:09
【问题描述】:

在没有捆绑包的情况下,要求 js 可以正常工作。但是每当我使用捆绑包时,我尝试导入的模块都会超时。

这是我使用 asp.net mvc bundler/minifier 构建捆绑包的方法

bundles.Add(new ScriptBundle("~/bundles/test").Include(
            "~/scripts/jquery-{version}.js",
            "~/scripts/bootstrap.js",
            "~/scripts/moment.js"));

bundles.EnableOptimizations = true;

这是cshtml文件中的require js配置:

<script>
    require.config({
        baseUrl: "/scripts",
        paths: {
            jquery: "jquery-1.11.2"
        },
        waitSeconds: 20,
        shim: {
            bootstrap: {
                deps: ['jquery']
            }
        },
        bundles: {
            '@Scripts.Url("~/bundles/test").ToString()': [
                'jquery',
                'bootstrap',
                'moment'
            ]
        }
    });
    require(["app/main/test"]);
</script>

以及页面的js(app/main/test):

require(['jquery', 'moment'], function ($, moment) {
    console.log(moment().format());
});

Jquery、bootstrap 和 moment 库在我创建的测试包中,但我在加载页面时遇到了加载超时。

这是 chrome 检查器错误:

有什么想法吗?

提前致谢。

【问题讨论】:

    标签: asp.net-mvc-5 requirejs timeout


    【解决方案1】:

    发生这种情况是因为您根本不需要捆绑包。您的 require 调用只有 jquery 和 moment。您已经提供了 jquery 文件路径,因此 requirejs 使用该路径下载并提供 jquery 模块。但由于暂时没有路径定义,它只是您创建的包的一部分。因此 requirejs 尝试通过其模块名称作为路径下载时刻,从而引发错误。

    一个简单的解决方法是要求 bundle 本身。

    require(['@Scripts.Url("~/bundles/test").ToString()'], function(bundle){
       //At this point jquery, moment and bootstrap will be loaded. 
    });
    

    您可以在上面的示例中直接从全局命名空间中选择使用 jQuery,也可以尝试在下面的示例中单独要求它们。我不确定,但由于循环依赖,您可能会在下面的示例中出错。

    require(['@Scripts.Url("~/bundles/test").ToString()', 'jquery', 'moment'], function(bundle, $, moment){
           //At this point jquery, moment and bootstrap will be loaded. 
        });
    

    【讨论】:

      【解决方案2】:

      只需从您的捆绑包中删除 'jquery'

      bundles.Add(new ScriptBundle("~/bundles/test").Include(
              "~/scripts/bootstrap.js",
              "~/scripts/moment.js"));
      
      ...
      bundles: {
          '@Scripts.Url("~/bundles/test").ToString()': [
              'bootstrap',
              'moment'
           ]
      }
      ...
      

      您已经在路径中指定了它

      paths: {
          jquery: "jquery-1.11.2"
      },
      

      似乎 require.js 将模块映射到包,因此一旦作为包的一部分的模块被加载,该包就不会再次加载。

      【讨论】:

        猜你喜欢
        • 2012-09-09
        • 1970-01-01
        • 2017-08-22
        • 1970-01-01
        • 2012-01-24
        • 1970-01-01
        • 2014-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多