3 reasons you shouldn’t bundle AngularJS with RequireJS

CWC
3 Min Read

Using RequireJS with AngularJS

This by itself adds a degree of complexity that is only justified if you have a really big single-page app, with a lot of views, for which you don’t want to charge the code in one shot.

Although it is perfectly possible, AngularJS was not designed to have this lazy loading logic.

Using RequireJS with AngularJS but bundling all the files together

Not this doesn’t make sense. If you bundle all the files together in one single js file, RequireJS is useless for an AngularJS app. You could still think to make use of the RequireJS modules, but AngularJS already gives you that with DI (dependency injection), so you’ll neither get the AMD (async module dependency), neither the lazy loading out of RequireJS.
For me you should just drop it and use plain AngularJS code bundled all together.

How you build your bundles carefully

AngularJS requires a certain order when it comes to loading your scripts:

  1. angularjs scripts (the angularjs file and all other angular modules)
  2. app.js (the app file that contains the app initialization)
  3. everything else (all other app controllers, directives, factories, etc…)

So if you just say to bundle a certain directory, there’s no warranty that this order is respected.

Then what should be the best practice ?

  1. Drop RequireJS. You don’t need it in this case.
  2. Separate scripts into 2 bundles:
    vendor.js that includes all the vendor scripts like angular, jquery and others that you need
    application.js that includes all the application scripts
    This will make sure you’ll take the most out of the client browser cache because chance are high that whenever you have a new version, only the app scripts changed.
    Also make sure that the vendor.js is loaded before the application.js
  3. Personally I prefer using the VS WebEssentials to build my bundles.
    I have much more control over how the bundle is created
    http://vswebessentials.com/features/bundling
    I even built a server-side control that lets me choose in the web.config if I want the bundle or all the single files to be rendered (for debugging).

Conclusion

Bundling AngularJS files that are wrapped in RequireJS modules is a combination that doesn’t make sense.  In my opinion you’re not taking any advantage of RequireJS, you’re only getting the problems. I believe that in this case you should drop RequireJS and keep the bundles. Bundle all those plugins in the vendor bundle and you’re set.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version