Skip to main content

Angular - Js Modules vs NgModules

JavaScript Modules vs. NgModules

Prerequisites

A basic understanding of JavaScript/ECMAScript modules.

JavaScript and Angular use modules to organize code, and though they organize it differently, Angular apps rely on both.

JavaScript modules

In JavaScript, modules are individual files with JavaScript code in them. To make what’s in them available, you write an export statement, usually after the relevant code, like this:
export class AppComponent { ... }

Then, when you need that file’s code in another file, you import it like this:
import { AppComponent } from './app.component';

JavaScript modules help you namespace, preventing accidental global variables.

NgModules

NgModules are classes decorated with @NgModule. The @NgModule decorator’s imports array tells Angular what other NgModules the current module needs. The modules in the imports array are different than JavaScript modules because they are NgModules rather than regular JavaScript modules. Classes with an @NgModule decorator are by convention kept in their own files, but what makes them an NgModule isn’t being in their own file, like JavaScript modules; it’s the presence of @NgModule and its metadata.
The AppModule generated from the Angular CLI demonstrates both kinds of modules in action:
  1. /* These are JavaScript import statements. Angular doesn’t know anything about these. */
  2. import { BrowserModule } from '@angular/platform-browser';
  3. import { NgModule } from '@angular/core';
  4.  
  5. import { AppComponent } from './app.component';
  6.  
  7. /* The @NgModule decorator lets Angular know that this is an NgModule. */
  8. @NgModule({
  9. declarations: [
  10. AppComponent
  11. ],
  12. imports: [ /* These are NgModule imports. */
  13. BrowserModule
  14. ],
  15. providers: [],
  16. bootstrap: [AppComponent]
  17. })
  18. export class AppModule { }

The NgModule classes differ from JavaScript module in the following key ways:
  • An NgModule bounds declarable classes only. Declarables are the only classes that matter to the Angular compiler.
  • Instead of defining all member classes in one giant file as in a JavaScript module, you list the module's classes in the @NgModule.declarations list.
  • An NgModule can only export the declarable classes it owns or imports from other modules. It doesn't declare or export any other kind of class.
  • Unlike JavaScript modules, an NgModule can extend the entire application with services by adding providers to the @NgModule.providers list.

More on NgModules

For more information on NgModules, see:

Comments