简体   繁体   中英

RequireJS dependency undefined in callback method

I started to use RequireJS , the dependency loads fine but in the callback method all dependencies are undefined .

require.config({
    baseUrl: 'js',
    paths: {
        angular: '../lib/angular/angular',
        myApp: 'app',
        states: 'app-states',
        controllers: 'controllers',
        filters: 'filters',
        services: 'services',
        oauth2: 'oauth2'
        //async: 'lib/require/async'
    },
    shim: {
        'myApp': {
            deps: ['angular']
        },
        'states' : {
            deps: ['angular', 'myApp']
        },
        'controllers': {
            deps: ['angular', 'myApp']
        },
        'filters': {
            deps: ['angular', 'myApp']
        },
        'services': {
            deps: ['angular', 'myApp']
        }       
    }
});

require(['angular', 'myApp', 'states', 'controllers', 'filters', 'services'], function(angular, myApp, states, controllers, filters, services) {
    'use strict';
    console.log('requireJs done');
    console.log(angular);
    console.log(myApp);
    angular.bootstrap(document, ['myapp']);
}); 

If I just require angular , the callback method is not called. I was wondering why.

require(['angular', function(angular) {
    console.log("requireJS done");
}]);

You're not exporting any values from those libraries. For shims you need to specify the variable to be exported before you can reference them. Since you're not exporting anything, the variables are set to null.

Exporting looks like this:

shim: {
    "angular": {
        exports: "angular"
    }
}

AMD/Requirejs works by pulling a value out of the files that it loads and setting that to the named argument in the callback function. For normal AMD files, thats whatever the return value of the function passed to define is, or the object within define. But for shims, you need to pick a variable, usually the namespace of the libary. That allows you to simulate AMD for namespace based libaries

You can see the documentation section on shims for more details.

Your syntax is wrong, the array of dependencies should the be the first argument.

Try

require(['angular'], function(angular) {
    console.log("requireJS done");
});

I had to export some library, to be available in my callback.

shim: {
    'angular': {
        exports: 'angular'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM