Search code examples
angularjsangular-moduleangular-factory

Is it ok to write multiple Angular component in a single file?


I am about to write a common Angular module which can be used as a plug and play module in my application.

What I want

I want to put the module definition and all its factory, directive, constants in a single js file, example:

angular.module('commonModule', [])
.factory(...)
.directive(...)
.constant(...)

Why because

Whenever a developer wants to use my module he/she just need to call a single js file and just need to inject my module in their module.

What is my problem

I have read the John papa's Angular 1 good practice style guide, he told that it is good to define a single component in a file, but here I am doing the opposite so what should I do?


Solution

  • Separate. Just so and not otherwise.

    Keeping components separately is one of the best practices in programming world. No matter if you have few lines of code at the moment, later code will increase. Doing so from the beginning you cultivate a literate programming discipline. Bad practice to come up with a bunch of exceptions in the rules, like "if I have few lines of code I can write all components of my app in one single file". It makes rules and possibility to follow them more complicated.

    Whenever a developer wants to use my module he/she just need to call a single js file and just need to inject my module in their module.

    Correct. For consumer it is very convenient to include just one single file in his/her project. But it is bad for code maintenance. So just use any JS bundler to concatenate all dependencies in one result file so consumers can just inject it in their module.