Thursday, April 24, 2014

Angular.js feature based file organisation

We mostly see type based organization being used for angular.js projects where files of same type (controllers, services, directives etc) are grouped in to different folders. While this approach is a simple and clean one, it starts to pain quickly.

Slowly I am moving towards feature based folder structure / organization for my angular.js projects. Here files are grouped by feature. For example, I might have a login folder which will contain core services and controllers which relates to login / auth processes (LoginController.js, User.js, LoginService etc).

Each such feature based folder has one file which declares the module and contains the config and run block for the module. Only thing to consider here is that the order in which files are loaded. The file containing the module declaration must be loaded before those files which uses it (defines services, controllers etc on the module).

If you are using lineman or similar grunt tools, this is easily done by reordering the file list. The rule I have is that first include the main application module. then include all module using a pattern similar to "path-to-files/**/*.module.js" and then include individual code file using a catch all pattern "path-to-files/**/*.js".

This also helps in testing modules separately and clearly helps us to define the modules - using the module feature of angular.js to the fullest.

Another useful trick is to define a constant on each module which contains all required configuration for the module. Example, define a loginConfig constant on login module which will hold URls to the varius API end points, event names triggered by the module and so on. It also helps us to easily mock the config object during testing.

No comments:

Post a Comment