用 RequireJS 加载 Backbone 出现 undefined


图片描述

代码如下:


 requirejs.config({
    paths: { }
    ,shim: {
        'backbone': {
            deps: ['underscore', 'jquery']
            ,exports: 'Backbone'
        }
        ,'localstorage': {
            deps: ['backbone']
        }
        ,'bootstrap': ['jquery']
        ,'underscore': {
            exports: '_'
        }
    }
    ,packages: [
        {
            name: 'jquery'
            ,location: 'libs'
            ,main: 'jquery-2.0.2.min'
        }
        ,{
            name: 'bootstrap'
            ,location: 'bootstrap'
            ,main: 'bootstrap'
        }
        ,{
            name: 'backbone'
            ,location: 'backbone'
            ,main: 'backbone'
        }
        ,{
            name: 'underscore'
            ,location: 'underscore'
            ,main: 'underscore'
        }
        ,{
            name: 'backbone.localstorage'
            ,location: 'backbone.localstorage'
            ,main: 'backbone.localstorage'
        }
        ,{
            name: 'react'
            ,location: 'react'
            ,main: 'react'
        }
    ]
});
requirejs(['require', 'underscore', '/js/backbone/backbone.js'],function(require, _, B){
    var bac = require('/js/backbone/backbone.js');
    console.log(B)
    //console.log(bac)
})

backbone requirejs JavaScript

finally 10 years, 2 months ago

我记得 backbone 不需要 shim

backbone 源码开头是这样的:


 // 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, _, $);
    });

意思是说如果 define 函数有定义的话,则用 define 来处理依赖的模块。因为你用了 require ,所以自然 define 函数的是定义了的,所以你需要让 Backbone 能够找到 underscore jquery

试试把 jquery 加到path里, Backbone shim 去掉吧:


 path:{
    'jquery':libs/jquery-2.0.2.min
}

wakaka answered 10 years, 2 months ago

因为你require的时候用的模块名是 /js/backbone/backbone.js ,没有用上前面的 shim 配置,Backbone又没有带amd兼容,所以拿不到引用


更新,backbone新版带了不甚标准的amd兼容(define但没有返回引用而还是全局暴露backbone),因为没有返回引用所以还是要shim

唤潮鲛姬娜美 answered 10 years, 2 months ago

requirejs需要加载的js符合 AMD规范
对于非AMD规范的库 requirejs可以通过配置 shim 加载

你代码里已经配置过shim部分了 因此加载部分写成这样就可以了


 requirejs(['require', 'underscore', 'backbone'],function(require, _, Backbone){
    console.log(Backbone);

})

parapa answered 10 years, 2 months ago

Your Answer