require.js shim for lib jquery,marionette,backbone,underscore

时间:2016-11-11 02:49:20

标签: javascript backbone.js requirejs marionette

我曾经链接过库:

shim: {
    backbone: {
        deps: ["jquery", "underscore"],
        exports: "Backbone"
    },
    marionette: {
        deps: ["backbone"],
        exports: "Marionette"
    },
    angular: {
        exports: "angular"
    }
}

但现在我已经读过这些libs使用AMD并且不需要shim属性!是吗?

main.js

paths: {
    marionette: "backbone.marionette"
}

some.js

define( "util",

        ['marionette'],
        function(Marionette){
            //test arguments!
            //console.log($)
            //console.log(jQuery)
            //console.log(Backbone)
            //console.log(_)
            console.log(Marionette) //exist!

        }
);

1 个答案:

答案 0 :(得分:1)

如果第三方脚本不兼容AMD,则必须使用shims

您可以检查脚本是否与AMD兼容,如果代码顶部的代码确实如此:

(function(root, factory) {

  // Set up Backbone appropriately for the environment. Start with AMD.
  if (typeof define === 'function' && define.amd) {
    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    });

  // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  } else if (typeof exports !== 'undefined') {
    var _ = require('underscore'), $;
    try { $ = require('jquery'); } catch(e) {}
    factory(root, exports, _, $);

  // Finally, as a browser global.
  } else {
    root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
  }

}(this, function(root, Backbone, _, $) {
    // ....
}

以下是我的项目中的配置文件的示例:

shim: {

    // jQuery Mobile
    "jquerymobile": ["jquery"],

    // Twitter Bootstrap jQuery plugins
    "bootstrap": ["jquery"],

    // jQueryUI
    "jqueryui": ["jquery"],

    // jQuery Cookie
    "jquery.cookie": {
        deps: ["jquery"],
        exports: "jquery.cookie"
    },

    // jQuery easing functions
    "jquery.easing" : {
        deps: ["jquery"],
        exports: "jquery.easing"
    },

    // Shim backbone to resolve conflicts on minification
    "backbone": {
        deps: ['underscore', 'jquery'],
        init: function(_, $) {
            return this.Backbone = Backbone.noConflict();
        }
    },

    // Backbone.validateAll plugin that depends on Backbone
    "backbone.validateAll": ["backbone"],

    "backbone.paginator" : {
        deps: ["backbone"],
        exports : "Backbone.Paginator"
    },

    "backgrid" : {
        deps : ['jquery', 'underscore', 'backbone'],
        exports: "Backgrid"
    },

    "backgrid.paginator" : {
        deps: ["backbone", "backgrid"],
        exports : "Backgrid.Paginator"
    }

}