lefedt logo

ngDefine: A minimal AngularJS in RequireJS/AMD boilerplate

26 Jul 2013 / posted by Nikku

Developing web applications using AngularJS is fun. Modularizing your application using RequireJS/AMD modules is nice, too unless you enjoy it to shuffle around <script /> tags everytime you include another javascript file into the application.

This post introduces ngDefine, a tiny library I have created that makes both technologies get to know each other.

Integration in a Nutshell

ngDefine integrates AngularJS and RequireJS by wrapping define and adding a little bit of AngularJS flavour to it.

Defining a module using ngDefine may look as follows:

ngDefine('app', [
  'jquery',
  'module:app.controllers:',
  'module:app.services:',
  'module:app.directives',
  './local'
], function(module, $) {

  // module = { name: 'app', .. }

  module.config(function($routeProvider) {
    $routeProvider.when( ... );
  });
});

It calls the function ngDefine with the name of the AngularJS module, a list of dependencies and a factory function. Dependencies may contain references to AngularJS modules, denoted by module:{moduleName}. Those get translated to actual file resources before the whole list of dependencies is resolved via RequireJS. ngDefine wires together the Angular module and passes it into the factory function along with all resolved AMD dependencies.

Features

The ngDefine integration offers a number of benefits over plain AngularJS applications:

  • Improved modularization: AngularJS modules may be packaged into reusable AMD modules.
  • Integration of external libraries: Non-AngularJS dependencies may easily be declared via AMD dependencies.
  • Minimal RequireJS boilerplate: The amount of RequireJS boilerplate in the application code is kept at a minimum (only the ngDefine wrapper is needed).
  • Minification: The integration can be minified. After minification module definitions are stripped down to plain AngularJS/RequireJS code after minification.

In addition it helps to avoid common pitfalls in AngularJS applications such as unintended module re-definition.

Additional Resources

If you would like to learn more, check out the project website or its home on GitHub.

Feel free to give feedback on the project and report bugs on the issue tracker.