What is the difference between Angular and JavaScript modules? – Organizing Your Application

Almost all programming languages offer a way for their developers to organize functions, classes, and variables in one or more files, allowing greater maintainability and separation of concerns.

In JavaScript, sometime after its creation and several proposals, the concept of language modules was consolidated. The best way to explain this concept is to demonstrate it with an example. First, we create a sum.mjs file – the sum function that receives two numbers and returns their sum. The important thing here is that we use the export keyword to indicate that we want to use it in a scope outside of its source file:
export function sum(numberA,numberB){
  return numberA + numberB;
}

 In the index.mjs file, we will use the created function and, for that, we make the declaration in the first line of the file. Using the reserved word import, we indicate which function and which file it is from:
import {sum} from ‘./sum.mjs’;
const numberA = 5;
const numberB = 10;
console.log(sum(numberA,numberB));

You may be wondering why the .mjs extension is used. It’s because, in the example, we are using Node.js to execute, and this type of module – ECMAScript modules (ESM), as the official name of the Javascript language is ECMAScript – was introduced in version 14.

Angular, as well as all other SPA frameworks, uses JavaScript modules in its development, and we can notice in any Angular component or service that we export the classes and import using the ESM:
import { Component } from ‘@angular/core’;
@Component({
  selector: ‘app-home’,
  templateUrl: ‘./home.component.html’,
  styleUrls: [‘./home.component.css’]
})
export class HomeComponent {

In the preceding code snippet, we are importing the Component decorator from the @angular/core library and exporting the HomeComponent class to use in other parts of our project.

Modules type

Now that we understand and have reinforced the concept of modules in the Angular framework, let’s divide our application and make better use of this feature. There is no fixed rule for organizing the modules of an application, but the Angular team and the community suggest the separation of modules based on the grouping of functionalities with common characteristics.

Based on this thought, we can have the following types of Angular modules:

  • Business domain modules
  • Component modules

Write a Comment

Your email address will not be published. Required fields are marked *