Building and Testing
One file, one module
In Chapter 1, Angular Zen, we've seen that AngularJS modules can depend on each
other. This means that in the AngularJS application we need to deal with both
directories hierarchy and modules hierarchy. Now we are going to dig more into
those topics in order to come up with pragmatic recommendations for organizing
AngularJS modules and their content.
There are basically three approaches we could take to relate individual files and
AngularJS modules:
- Allow multiple AngularJS modules in one JavaScript file
- Have AngularJS modules spanning multiple JavaScript files
- Define exactly one AngularJS module per JavaScript file
Defining multiple modules in one file is not extremely harmful but it might result in
big files with hundreds of lines of code. On top of this it is harder to find a particular
module in the code base as we need to locate both a file in a file system, and a module
within a file. While having multiple modules in one file might work for very simple
projects it is not optimal for larger code bases.
Having one module spanning over multiple files is something that should be
probably avoided. As soon as the code for one module is spread across multiple
files we need to start thinking about load order of those files: module declaration
need to come before providers are registered. Additionally, such modules tend
to be bigger and as such harder to maintain. Big modules can be particularly
undesirable for unit testing, where we want to load and exercise units of code
as small as practically possible.
Out of the three proposals having exactly one AngularJS module per file seems to
be the most sensible approach.
Stick to the one file equals one AngularJS module principle. This will
allow you to maintain relatively small, focused files and modules.
Additionally you won't be concerned with the load order of those files.
Also it will be possible to load individual modules under unit tests.