I'm a newbie to Angular.js and trying to understand how it's different from Backbone.js... We used to manage our packages dependencies with Require.js while using Backbone. Does it make sense to do the same with Angular.js?
-
Another blog and seed project: http://www.startersquad.com/blog/angularjs-requirejs – iwein Oct 01 '13 at 18:35
-
20No - Don't use require.js OR browserify with Angular.JS there is simply no need to do that - AngularJS has a module system and using another module system above it will make your life unnecessarily hard. I've followed the answers in this thread and wasted too many hours on something that was completely needless. Please read this article that explains why not: https://medium.com/@dickeyxxx/best-practices-for-building-angular-js-apps-266c1a4a6917 – VitalyB Aug 01 '14 at 20:32
-
Read this to understand the difference between angular and require modules http://juristr.com/blog/2014/07/lazy-angular-modules/ – pilavdzice Sep 18 '14 at 23:15
-
If you need to asynchronously load Angular modules and your modules — use RequireJS. If you have all your controllers, directives, etc. concatenated in one script.js file — of course you don't need RequireJS, it is totally useless in this case. – artuska Oct 06 '14 at 22:20
-
1here is a great video that explains why it's a good idea and shows how to use requireJS with angularJS https://www.youtube.com/watch?v=4yulGISBF8w#t=142 – gskalinskii Oct 17 '14 at 20:30
-
@PHearst, the AngularJS Lazy Loading is avalaible in a stable version? – Ronye Vernaes Mar 17 '15 at 16:56
-
2@VitalyB Nice article! I favor loading applications in small pieces. [It will cost nothing soon enough](https://www.zunzun.se/blog/). Heck, it doesn't cost anything for me right now. – dsign Sep 09 '15 at 12:14
14 Answers
Yes it makes sense to use angular.js
along with require.js
wherein you can use require.js
for modularizing components.
There is a seed project which uses both angular.js and require.js
.

- 10,591
- 9
- 64
- 104

- 7,783
- 5
- 31
- 41
-
108The seed project mentioned above has not been touched for a year so I've created a [new one using latest AngularJS and RequireJS](https://github.com/tnajdek/angular-requirejs-seed) with full support for testacular-driven testing. – tnajdek Feb 25 '13 at 19:44
-
2@tnajdek, I updated the link in Anshu's answer to point to the one you suggest. – David Rivers May 24 '13 at 14:24
-
7Note that neither of those seed projects are endorsed by the Angular team. Require is a pattern that made more sense in other contexts, and shoe-horning it into Angular is not, IMHO, a best-practice. – XML Sep 06 '13 at 04:51
-
2The O'Reilly AngularJS book by Brad Green & Shyam Seshadri (released April of this year) also recommends adding RequireJS early in the growth of an Angular project, and lays out details quite clearly. – bjorke Nov 16 '13 at 19:03
-
1I'd much rather do everything at build time 1. http://browserify.org/ 2. https://www.npmjs.org/package/gulp-angular-filesort – A-Dubb Jul 08 '14 at 14:48
-
This seed project is misguided, because it still downloads all sections of the Angular app, even the ones that the user doesn't need to access. So your total initial download size is the same as-if you just concatenated everything using Gulp/Grunt. You should use AngularAMD if you want to do this properly. – ngDeveloper Apr 06 '15 at 19:04
-
@XMLilley There was a presentation at ngConf 2015 from a team at Google that demonstrated they used a package manager to lazy-load their application. They said it's necessary on their projects, because otherwise, the initial download for their app would be 24mb (concatenated and uglified). Using lazy-loading also let's them share common modules with other teams across many of their Google applications, so ie. they use the same authentication module in each application. – ngDeveloper Apr 06 '15 at 19:06
-
Right. So, for the world's largest and most complex angular applications, there is indeed a special use-case for lazy-loading. And there are indeed other use-cases for that. But that doesn't seem to be OP's question. His question isn't generally whether lazy-loading or AMD have value for certain use-cases. It's whether you need them, _by default_, in a basic Angular application. – XML Apr 07 '15 at 13:30
-
Having looked at that seed project, I'm really not sure I want to use require. It seems to add a lot of ugly boilerplate to every file. And especially considering @XMLilley's excellent answer below, I'm leaning towards a 'no'. – mcv Mar 07 '16 at 21:50
To restate what I think the OP's question really is:
If I'm building an application principally in Angular 1.x, and (implicitly) doing so in the era of Grunt/Gulp/Broccoli and Bower/NPM, and I maybe have a couple additional library dependencies, does Require add clear, specific value beyond what I get by using Angular without Require?
Or, put another way:
"Does vanilla Angular need Require to manage basic Angular component-loading effectively, if I have other ways of handling basic script-loading?"
And I believe the basic answer to that is: "not unless you've got something else going on, and/or you're unable to use newer, more modern tools."
Let's be clear at the outset: RequireJS is a great tool that solved some very important problems, and started us down the road that we're on, toward more scalable, more professional Javascript applications. Importantly, it was the first time many people encountered the concept of modularization and of getting things out of global scope. So, if you're going to build a Javascript application that needs to scale, then Require and the AMD pattern are not bad tools for doing that.
But, is there anything particular about Angular that makes Require/AMD a particularly good fit? No. In fact, Angular provides you with its own modularization and encapsulation pattern, which in many ways renders redundant the basic modularization features of AMD. And, integrating Angular modules into the AMD pattern is not impossible, but it's a bit... finicky. You'll definitely be spending time getting the two patterns to integrate nicely.
For some perspective from the Angular team itself, there's this, from Brian Ford, author of the Angular Batarang and now a member of the Angular core team:
I don't recommend using RequireJS with AngularJS. Although it's certainly possible, I haven't seen any instance where RequireJS was beneficial in practice.
So, on the very specific question of AngularJS: Angular and Require/AMD are orthogonal, and in places overlapping. You can use them together, but there's no reason specifically related to the nature/patterns of Angular itself.
But what about basic management of internal and external dependencies for scalable Javascript applications? Doesn't Require do something really critical for me there?
I recommend checking out Bower and NPM, and particularly NPM. I'm not trying to start a holy war about the comparative benefits of these tools. I merely want to say: there are other ways to skin that cat, and those ways may be even better than AMD/Require. (They certainly have much more popular momentum in late-2015, particularly NPM, combined with ES6 or CommonJS modules. See related SO question.)
What about lazy-loading?
Note that lazy-loading and lazy-downloading are different. Angular's lazy-loading doesn't mean you're pulling them direct from the server. In a Yeoman-style application with javascript automation, you're concatenating and minifying the whole shebang together into a single file. They're present, but not executed/instantiated until needed. The speed and bandwidth improvements you get from doing this vastly, vastly outweigh any alleged improvements from lazy-downloading a particular 20-line controller. In fact, the wasted network latency and transmission overhead for that controller is going to be an order of magnitude greater than the size of the controller itself.
But let's say you really do need lazy-downloading, perhaps for infrequently-used pieces of your application, such as an admin interface. That's a very legitimate case. Require can indeed do that for you. But there are also many other, potentially more flexible options that accomplish the same thing. And Angular 2.0 will apparently take care of this for us, built-in to the router. (Details.)
But what about during development on my local dev boxen?
How can I get all my dozens/hundreds of script files loaded without needing to attach them all to index.html manually?
Have a look at the sub-generators in Yeoman's generator-angular, or at the automation patterns embodied in generator-gulp-angular, or at the standard Webpack automation for React. These provide you a clean, scalable way to either: automatically attach the files at the time that components are scaffolded, or to simply grab them all automatically if they are present in certain folders/match certain glob-patterns. You never again need to think about your own script-loading once you've got the latter options.
Bottom-line?
Require is a great tool, for certain things. But go with the grain whenever possible, and separate your concerns whenever possible. Let Angular worry about Angular's own modularization pattern, and consider using ES6 modules or CommonJS as a general modularization pattern. Let modern automation tools worry about script-loading and dependency-management. And take care of async lazy-loading in a granular way, rather than by tangling it up with the other two concerns.
That said, if you're developing Angular apps but can't install Node on your machine to use Javascript automation tools for some reason, then Require may be a good alternate solution. And I've seen really elaborate setups where people want to dynamically load Angular components that each declare their own dependencies or something. And while I'd probably try to solve that problem another way, I can see the merits of the idea, for that very particular situation.
But otherwise... when starting from scratch with a new Angular application and flexibility to create a modern automation environment... you've got a lot of other, more flexible, more modern options.
(Updated repeatedly to keep up with the evolving JS scene.)
-
1The NG-Boilerplate seed project (https://github.com/ngbp/ngbp) also creates a single page webapp with one js file. Using a HTML5 manifest makes sure this file is only loaded once per version. – Federico Elles Jan 31 '14 at 10:25
-
2Though, as always, it depends. Many people use Require for their entire architecture, and need to integrate Angular into that ecosystem. It's a very different situation than when you're building apps in isolation. – Dave Nichol May 14 '14 at 17:35
-
2Agreed. But the OP's thrust seems to be: "If I'm building an application principally in Angular, and (implicitly) doing so in the era of Grunt, and I maybe have a couple additional library dependencies, does Require add clear, specific value beyond what I get by using Angular without Require?" And I believe, the answer is: no. If you have a huge application with 40 outside dependencies, or you can't control your CI environment, or your boss adores Require, or you adore Require, or Angular is only one piece of a larger application, etc., etc., then YMMV. – XML Jun 02 '14 at 13:41
-
1But since he doesn't seem to ask those questions, and since he simply mentions the alternate context of a Backbone app, he seems to ask: "does vanilla Angular need Require to manage its components effectively?" And the answer is: "not unless you've got something else going on." Also, this question came on the cusp of the Javascript CI movement, wherein we got much better ways to handle basic, physical 'script-loading'. If you have that problem solved, Require is basically about dependency-matching and encapsulation. Angular does both of those things for you. – XML Jun 02 '14 at 13:46
-
Google uses lazy-loading in some of it's AngularJS projects, because otherwise, the user would be downloading 24mb of files on the first page load (and this is with files uglified and concatenated). So yes, in complex applications it doesn't make to just concatenate all the sections, when there are sections the user won't be opening with every visit. – ngDeveloper Apr 06 '15 at 18:53
-
Right: in large complex applications, _which is not what the OP asked about_, there is an excellent use-case for it. For applications that aren't so incredibly large, and which we don't want to prematurely optimize for problems they don't have, it's a very different kind of question. – XML Apr 07 '15 at 13:35
-
I have two configuration files for two Grunt tasks that let me build to single-file using R.js, or just simply convert my CoffeeScript as I'm in development. AMD gives you flexibility — no one is really suggesting that you should consider 20KB savings versus a single-file: it's that RequireJS/AMD is the only future-proof architecture that handles *both* while Conventional Implementations lack explicit dependency management, and cannot scale. RequireJS is a "scalability" tool — and we really shouldn't build things in a way that *obviously* does not scale... – nerdfiles Apr 26 '15 at 15:25
-
@nerdfiles: RequireJS is indeed intended to be a 'scalability tool'... but it's one which has been superseded by much better scalability tools: Bower, NPM, Gulp, Grunt, Broccoli, Webpack, etc. So, let's look at the question another way: _"does it make sense to use a 'scalability tool' with Angular?"_ Yes! We're in agreement! Should your main scalability tool be Require.JS and the AMD pattern, _today_? Probably not, unless it solves a very particular problem for you that other, more modern scalability patterns don't already solve. – XML Dec 02 '15 at 05:24
-
@XMLilley How can you compare NPM, Bower,etc. with require.js ? NPM or Bower do dependency management on project/application level, but not on function level or do I miss something here? – Legends Jan 03 '17 at 20:44
-
Forgive me @legends, but I think you may indeed be missing something. On the one hand, Bower actually doesn't provide any improvements in modularity and dependency injection, although I didn't claim it did. But NPM is entirely based on module patterns that ensure explicit imports and dependency management at the level of _each module_, just as Require is based on the AMD pattern. For more, see: http://stackoverflow.com/a/31633281/800457. Then, maybe share a specific usage example where you feel NPM & CommonJS aren't comparable to Require & AMD. – XML Jan 05 '17 at 05:51
-
Can you point me to a link where AMD using NPM is explained. In my app I have a config where i have set all the relative paths to my modules/libs. And I have a build.config.js which I use together with r.js to make a build. All scripts have to be AMDified or shimed. Now I can use something like `require(['jquery','customMod'], function($, cm){ ... })` to load all depnedencies isolated from the global scope. How is that done with npm? – Legends Jan 05 '17 at 15:17
-
Hi, @Legends: for a specific technical solution, recommend you open a new question on SO. I've never tried integrating AMD with NPM, and can't recommend it except as a short-term bridge to a more sustainable, idiomatic solution. – XML Jan 07 '17 at 04:46
-
Hi @XMLilley, let me formulate it differently. Is the above mentioned possible with NPM, if your answer is yes, I will open a new q on SO. Thanks. – Legends Jan 07 '17 at 11:33
Yes, it makes sense.
Angular modules don't try to solve the problem of script load ordering or lazy script fetching. These goals are orthogonal and both module systems can live side by side and fulfil their goals.
Source: Angular JS official website

- 43,301
- 14
- 77
- 113

- 1,461
- 1
- 10
- 8
-
6If you use one module per js file you can load your angular module on any order. But if you want to put for example different services in different js files but you want to attach them on the same angular module you have to load the module declaration before the services declaration. So this is a an architecture decision. – Matohawk Aug 22 '13 at 14:41
-
@Tiago: Please provide a link to the location you sourced this from. I can't find it anywhere. I'm guessing that it came from an earlier version of the Angular docs, before Angular's patterns had become as well established, and before it had become clear that there are significant advantages to avoiding Require, at least for Angular components. – XML Sep 06 '13 at 04:42
-
@XMLilley: can you provide a link that explains the advantages of avoiding Require when using Angular? I'm deciding whether or not to use Require in my project and this sounds like it would be helpful. – Trevor Sep 27 '13 at 23:54
-
1I was unclear in my language here: there are significant advantages to leveraging Angular's own built-in module-loaders, and going with the grain of Angular patterns. The question is not whether to *avoid* Require, but rather whether there is value to adding an additional layer of complexity. What is clear is that Angular's built-in patterns will handily and elegantly address the need for the loading of Angular's own modules. If Require serves a purpose for loading modules outside of Angular context, then so be it. But using Require for Angular is extraneous. – XML Sep 30 '13 at 02:09
-
6@XMLilley all Angular does is give you dependency injection. The actual loading of the module is your responsibility. You can do this either by adding a script tag, having a build script or using requirejs. Angulars module system has no opinion on this. – gillesruppert Oct 30 '13 at 17:55
-
@gilesRuppert: Correct, although it's useful to be clear that 'module' means very different things in the AMD vs. Angular contexts. Either way, there's a file(s) to load. And the question is not *why not* use Require. There are many harmless but ineffective ways to make life more complicated; Require is as good as any. The question is *why* use Require? In an Angular context, in the era of high-bandwidth and Yeoman, where transmission overhead exceeds download time and concatenation is frictionless, where the module pattern is already enforced... what value can Require be demonstrated to add? – XML Nov 06 '13 at 03:00
-
how would you combine angulars module loading with game logic that is using amd (compiled with typescript) – FutuToad Jul 29 '14 at 12:49
This I believe is a subjective question, so I will provide my subjective opinion.
Angular has a modularization mechanism built in. When you create your app, the first thing you would do is
var app = angular.module("myApp");
and then
app.directive(...);
app.controller(...);
app.service(...);
If you have a look at the angular-seed which is neat starter app for angular, they have separated out the directives, services, controllers etc into different modules and then loaded those modules as dependancies on your main app.
Something like :
var app = angular.module("myApp",["Directives","Controllers","Services"];
Angular also lazy loads these modules ( into memory) not their script files.
In terms of lazy loading script files, to be frank unless you are writing something extremely large it would be an overkill because angular by its very nature reduces the amount of code you write. A typical app written in most other frameworks could expect a reduction in around 30-50% in LOC if written in angular.

- 26,841
- 6
- 63
- 59
-
5Indeed, it's better configure services in Angular.js than load modules with Require.js. This makes it easier to play with the $scope and services, as I played with Socket.io – Marco Godínez Dec 29 '12 at 06:13
Using RequireJS with AngularJS makes sense but only if you understand how each of them works regarding dependency injection, as although both of them injects dependencies, they inject very different things.
AngularJS has its own dependency system that let you inject AngularJS modules to a newly created module in order to reuse implementations. Let's say you created a "first" module that implements an AngularJS filter "greet":
angular
.module('first', [])
.filter('greet', function() {
return function(name) {
return 'Hello, ' + name + '!';
}
});
And now let's say you want to use the "greet" filter in another module called "second" that implements a "goodbye" filter. You may do that injecting the "first" module to the "second" module:
angular
.module('second', ['first'])
.filter('goodbye', function() {
return function(name) {
return 'Good bye, ' + name + '!';
}
});
The thing is that in order to make this work correctly without RequireJS, you have to make sure that the "first" AngularJS module is loaded on the page before you create the "second" AngularJS module. Quoting documentation:
Depending on a module implies that required module needs to be loaded before the requiring module is loaded.
In that sense, here is where RequireJS can help you as RequireJS provides a clean way to inject scripts to the page helping you organize script dependencies between each other.
Going back to the "first" and "second" AngularJS modules, here is how you can do it using RequireJS separating the modules on different files to leverage script dependencies loading:
// firstModule.js file
define(['angular'], function(angular) {
angular
.module('first', [])
.filter('greet', function() {
return function(name) {
return 'Hello, ' + name + '!';
}
});
});
// secondModule.js file
define(['angular', 'firstModule'], function(angular) {
angular
.module('second', ['first'])
.filter('goodbye', function() {
return function(name) {
return 'Good bye, ' + name + '!';
}
});
});
You can see that we are depending on "firstModule" file to be injected before the content of the RequireJS callback can be executed which needs "first" AngularJS module to be loaded to create "second" AngularJS module.
Side note: Injecting "angular" on the "firstModule" and "secondModule" files as dependency is required in order to use AngularJS inside the RequireJS callback function and it have to be configured on RequireJS config to map "angular" to the library code. You may have AngularJS loaded to the page in a traditional manner too (script tag) although defeats RequireJS benefits.
More details on having RequireJS support from AngularJS core from 2.0 version on my blog post.
Based on my blog post "Making sense of RequireJS with AngularJS", here is the link.

- 778
- 10
- 15
-
2It's actually best, when including a link, to summarize the contents of the link here on Stack Overflow. If your link were to ever break, which links do on the Internet, your answer here would be useless to future visitors. Consider an [edit] to bring in a summary and improve this post. Good luck! – jamesmortensen Jun 15 '14 at 08:21
-
3
-
Thanks for making these edits and explaining how RequireJS can help manage the dependencies to avoid issues with Angular trying to load something that doesn't yet exist. – jamesmortensen Jun 15 '14 at 19:35
-
i totally agree, it is best to use this approach for large applications if not you will be having multiple – I.Tyger Apr 10 '16 at 15:56
As @ganaraj mentioned AngularJS has dependency injection at its core. When building toy seed applications with and without RequireJS, I personally found RequireJS was probably overkill for most use cases.
That doesn't mean RequireJS is not useful for it's script loading capabilities and keeping your codebase clean during development. Combining the r.js optimizer (https://github.com/jrburke/r.js) with almond (https://github.com/jrburke/almond) can create a very slim script loading story. However since its dependency management features are not as important with angular at the core of your application, you can also evaluate other client side (HeadJS, LABjs, ...) or even server side (MVC4 Bundler, ...) script loading solutions for your particular application.

- 1,771
- 1
- 12
- 11
Yes, it does, specially for very large SPA.
In some scenario, RequireJS is a must. For example, I develop PhoneGap applications using AngularJS that also uses Google Map API. Without AMD loader like RequireJS, the app would simply crash upon launch when offline as it cannot source the Google Map API scripts. An AMD loader gives me a chance to display an error message to the user.
However, integration between AngularJS and RequireJS is a bit tricky. I created angularAMD to make this a less painful process:

- 3,892
- 2
- 16
- 35
Short answer is, it make sense. Recently this was discussed in ng-conf 2014. Here is the talk on this topic:

- 19,834
- 7
- 55
- 102
Yes it makes sense to use requireJS with Angular, I spent several days to test several technical solutions.
I made an Angular Seed with RequireJS on Server Side. Very simple one. I use SHIM notation for no AMD module and not AMD because I think it's very difficult to deal with two different Dependency injection system.
I use grunt and r.js to concatenate js files on server depends on the SHIM configuration (dependency) file. So I refer only one js file in my app.
For more information go on my github Angular Seed : https://github.com/matohawk/angular-seed-requirejs

- 301
- 3
- 10
It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

- 631
- 1
- 7
- 10
I would avoid using Require.js. Apps I've seen that do this wind up a mess of multiple types of module pattern architecture. AMD, Revealing, different flavors of IIFE, etc. There are other ways to load on demand like the loadOnDemand Angular mod. Adding other stuff just fills your code full of cruft and creates a low signal to noise ratio and makes your code hard to read.

- 508
- 1
- 4
- 20
Here is the approach I use: http://thaiat.github.io/blog/2014/02/26/angularjs-and-requirejs-for-very-large-applications/
The page shows a possible implementation of AngularJS + RequireJS, where the code is split by features and then component type.
-
3Even when the link give info to answer the question, an explanation of what the page show is a best practice. – juliocesar Feb 26 '14 at 18:34
Answer from Brian Ford
AngularJS has it's own module system an typically doesn't need something like RJS.
Reference: https://github.com/yeoman/generator-angular/issues/40

- 1,423
- 1
- 16
- 29
I think that it depends on your project complexity since angular is pretty much modularized. Your controllers can be mapped and you can just import those JavaScript classes in your index.html page.
But in case your project get bigger. Or you anticipates such scenario, you should integrate angular with requirejs. In this article you can see a demo app for such integration.

- 566
- 4
- 12