NOBLE M.O. NOBLE M.O. - 4 months ago 27
AngularJS Question

Multiple IIFE in angular js script and injecting using RequireJS

I need to inject my angularJs script files using RequireJS and it is working correctly. But I cannot write more than one iife in single file. Only one iife will get executed in this case. The following are my codes.

(function () {
define([
'angular'
], function () {
angular.module('framework', ['ui.router', 'pluggableViews'])
.controller('appCtrl', function ($scope) {
$scope.label = 'Test label';
});
});
})();

(function () {

define([
'angular'
], function () {

angular.module('framework').config(['$urlRouterProvider',
'$pluggableViewsProvider',
function ($urlRouterProvider, $pluggableViewsProvider) {

$urlRouterProvider.otherwise('/login');
}]);

});
})();


In the above code only the first iife is executed. Second iife is not getting any break point. How can I fix this issue while using requireJS? If I move both iife in to two separate files then it will work. But it will not be possible for me in all cases. Please suggest me a solution.

Answer

You have multiple anonymous define calls in the same file. This is something that RequireJS cannot handle. When RequireJS runs into an anonymous define, it uses the module name that was used to load the file as the module name it is going to assign to the module being anonymously defined. That's how the module gets its name. If you have more than one anonymous define in the same file, then what is RequireJS supposed to do? Two modules cannot have the same name, and it is not going to invent names for you. When more the one module is present in a single file, you have to name them explicitly by passing a name as the first parameter to define. (This is what the optimizer (r.js) does for you.)

(Theoretical aside: two different RequireJS context could each have a module with the same name but this cannot be a factor here because two modules loaded from the same file will be in the same context.)

Keep the two modules in separate files if you want to keep the anonymous define calls. Or name the modules if you absolutely must have them in a single file. I would keep them separate for development and let a bundler give them names when producing a bundle for deployment.