在RequireJS应用中使用bootbox

3

我有一个带有样例app.js文件:

requirejs.config({
    "baseUrl": "js/lib",
    "paths": {
      "jquery": "jquery",
      "app": "../app",
      "bootstrap": "bootstrap/js/bootstrap.bundle",
      "bootbox": "bootbox.min"
    },
    "shim": {
        "bootstrap": {
            "deps": ["jquery"],
            "exports": 'bootbox'
             },
        "main": { "deps": ["jquery","bootstrap"] },
        "bootbox": {
            "deps": ["jquery","bootstrap"],
            "exports": 'bootbox'
        },
    }
});

require(['jquery','bootstrap','bootbox'], function($){

    $(function(jquery) {
        bootbox.alert("bla")
    });
});

当我运行我的页面时,我可以看到正确的JS文件被获取:

enter image description here

...然而我的代码失败了:

bootbox.alert("bla")

错误提示:

ReferenceError:bootbox未定义

我可能缺少某些简单的东西(如果这是新手错误,我很抱歉 - 我仍在努力理解此库)


1
我们需要保持与 https://github.com/twbs/bootstrap/pull/24783 的连接,并查看它是否真正解决了问题。 - Machado
1个回答

1
不要在Bootbox中使用shim。如果您查看Bootbox的源代码,您会发现它调用define,将其注册为适当的AMD模块。 shim选项仅适用于不是适当的AMD模块的代码。现在,在Bootbox中的define执行以下操作:
define(["jquery"], factory);

它设置了对jQuery的依赖,但这是错误的,因为实际上Bootbox还依赖于存在Bootstrap。所以我们需要解决这个问题。以下展示了如何解决它。您可以使用一个map配置选项,这样当Bootbox需要jQuery时,它就会得到Bootstrap。并且您为Bootstrap设置了一个shim,以便除了依赖于jQuery之外,它的模块值与jQuery($)相同。
没有map设置,不能保证Bootstrap会在Bootbox之前加载,您将面临竞争条件:有时它会工作,有时不会。

requirejs.config({
  baseUrl: ".",
  paths: {
    jquery: "//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min",
    bootstrap: "//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min",
    bootbox: "//github.com/makeusabrew/bootbox/releases/download/v4.4.0/bootbox.min"
  },
  shim: {
    "bootstrap": {
      "deps": ["jquery"],
      // We set bootstrap up so that when we require it, the value with get is just $.
      // This enables the map below.
      "exports": "$"
    },
  },
  map: {
    // When bootbox requires jquery, give it bootstrap instead. This makes it so that
    // bootstrap is **necessarily** loaded before bootbox.
    bootbox: {
      jquery: "bootstrap",
    },
  }
});

require(["jquery", "bootbox"], function($, bootbox) {
  $(function(jquery) {
    bootbox.alert("bla");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />


你太棒了!运行得非常顺利 :) - Andrew Newby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接