Reputation: 10536
I have an AngularJS project with a shared
directory, in which there are several shared components.
- shared
- index.js
- alert
- index.js
- alert.component.js
- alert.controller.js
- alert.tpl.html
- alert.scss
- logging
- index.js
- logging.component.js
- logging.controller.js
- logging.tpl.html
- logging.scss
The code is written in a modular way in ES6. So for instance alert.component.js
might look like this:
import controller from './alert.controller'
export const Alert = {
controller,
templateUrl: 'shared/alert/alert.tpl.html'
};
I would like to have one AngularJS module called shared
in which both components are defined. My question is on what level should I actually define the component. Should it be inside the component directory (shared/alert/index.js
) or in the shared directory (shared/index.js
).
In the first case, the file shared/alert/index.js
, would look like this:
import { Alert } from './alert.component';
angular.module('shared').component('Alert', Alert);
And in the second case, the file would look like this:
export { Alert } from './alert.component';
And then both components would be defined in shared/index.js
:
import { Alert } from './alert';
angular.module('shared').component('Alert', Alert);
import { Logging } from './logging';
angular.module('shared').component('Logging', Logging);
The first case seems a bit odd to me, since I kind of let the component add itself to the application. In the second case however I end up with a huge index.js
file, if I have many shared components. So I was wondering what other up and down sides each of these approaches has and if there any best practices?
Upvotes: 0
Views: 141
Reputation: 223114
As with any 'best practice', the preferable way to do this is deduced from possible problems that can appear in this situation.
angular.module('shared')
module getter is generally an antipattern, especially in modular environment. It should be evaluated after the module was defined with angular.module('shared', [])
module setter. Doing the opposite will result in race condition and error.
In the first case importing shared/alert/index.js
in tests or another module will result in error because shared
module wasn't defined yet.
In the second case there will be no such problem, but only if shared
module is defined in shared/index.js
.
The approach that plays well with ES modules is one module per file. The result is highly modular application with relatively low amount of boilerplate code. The benefits are reusability and testability, submodules can depend on each other but aren't coupled to share
.
This is important consideration if some of submodules contain items that affect the entire application - decorators, config/run blocks, third-party modules that contain them (router).
Upvotes: 2