error loading jquery-ui in require.js config for f

2019-09-15 05:40发布

问题:

I'm trying to load a jQuery control called fancytree and this control depends on jquery-ui. I'm getting an error saying that it hasn't loaded jquery-ui from the path I've given. Fancytree also depend on another file called fancytree.table as well.

My directory structure is like this

js
    /app
        ....
    /lib
        /jquery
        /underscore
        /backbone
    /vendor
        /jquery-ui
        /fancytree

Error:

jquery.js:2 Uncaught Error: Fancytree assertion failed: Fancytree requires jQuery UI (http://jqueryui.com)(…)

config:

require.config({
    // The shim config allows us to configure dependencies for
    // scripts that do not call define() to register a module

    paths: {
        'jquery': '../lib/jquery/jquery',
        'underscore': '../lib/underscore/underscore',
        'backbone': '../lib/backbone/backbone',     
        'text': '../lib/text/text',
        'jquery-ui': '../vendor/jquery-ui/jquery-ui',
        'fancytree': [      
            '../vendor/fancytree/fancytree',
            '../vendor/fancytree/fancytree.table'
        ],      
    },
    shim: {

        underscore: {
            exports: '_'
        },
        backbone: {
            deps: [
                'underscore',
                'jquery'
            ],
            exports: 'Backbone'
        },
        'jquery-ui': {
            exports: "$",
            deps: ['jquery']
        },      
    },
    baseUrl: '/js/app',

});

view:

define(['jquery-ui', 'fancytree', 'require'], function(ui, fancytree, require){

    'use strict';

    var $ = require('jquery'),
        _ = require('underscore'),  
        Backbone = require('backbone'),
        tpl = require('text!templates/categories.html'),
        template = _.template(tpl);


    return Backbone.View.extend({
        el: $('#tree'),
        initialize: function() {

            this.listenTo( this.collection, 'reset add change remove', this.render, this );
            this.collection.fetch();
        },
        initFancyTree: function() {
            console.log('tree');
            $('#fancytree').fancytree();

        },
        render: function() {                
            this.$el.html(template());
            //this.initFancyTree();
            return this;
        }
    });
})

回答1:

The error comes from line 85 of Fancytree:

_assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)");

To solve that, add a shim for fancytree:

'fancytree': {
    deps: ['jquery-ui']
}, 

This is necessary because Fancytree is not defined as a module and depends on globals. Most library now uses something like UMD (Universal Module Definition).