banner



How To Register A Module In Angular Cli

No CLI — Learn how your Athwart App is put together

image credit BobSmith via Flickr

AngularInDepth is moving away from Medium. More recent articles are hosted on the new platform inDepth.dev . Thanks for being part of indepth motility!

In this post, Maxim Koretskyi and I, are going to testify you how to set-upwardly an Angular project from scratch. You lot volition learn about all the different pieces required for a performance Angular app, including the different Angular packages, settings upwards TypeScript, configuring a module loader and bootstrapping the main component of the app.

Why?

Basically, the CLI is a great tool and time saver, but at the same fourth dimension it is opinionated and hides from you some of the internals. When you later want to ready server side rendering, for case, y'all have to really understand how things are wired together. This is where this post comes handy. Also, the CLI installs all packages that you might need during development. This is a right arroyo but by having all possible packages installed it's difficult to acquire which minimal dependencies are required to setup the simplest Angular project. The projection yous'll exist assembling here will accept as minimum dependencies as possible.

Game plan

We volition start by setting up the module loader, and so utilise npm to install Angular and its dependencies, equally well as some tools and polyfills nosotros volition need, such as the TypeScript compiler. Finally, we will create a minimal application skeleton, and write the code for bootstrapping it. If everything goes well, nosotros will have our first "from-scratch" Angular app running in the browser merely in a few minutes!

In our app, nosotros will try to replicate a folder construction that follows the Angular Style Guide, which is also followed by the CLI.

Modules

Most Angular tutorials utilise TypeScript and i of its key features — modules. The module system provided by TypeScript is based on the ECMAScript modules standard (a.thou.a ESM or ES6 modules). The motivation for using modules is to provide encapsulation, thus decreasing coupling and complexity.

It is of import to note that Athwart has a different concept for Modules. You should non confuse Athwart and ESM modules. They serve absolutely different purposes. In Athwart, modules serve as an encapsulation mechanism for the application building blocks — components, directives, pipes. And while in that location is no encapsulation for services, modules still act as container where services tin can exist registered. ESM modules, on the other hand, are not specific to Angular and act as an encapsulation mechanism for generic JavaScript/TypeScript code. You tin read more about Angular modules in Fugitive common confusions with modules in Angular.

Until recently JavaScript didn't have congenital-in module mechanism so the community came upward with a few unfortunately incompatible standards — CommonJS Modules and Asynchronous Module Definition (AMD). The major update to ECMAScript specification commonly referred to as ES6 or ES2015 introduced native modules back up into JavaScript language. Notwithstanding, the browser back up at the time of writing is still very express. Hence, we need a tool to enable loading ESM modules into a browser.

For this purpose, we are going to utilize SystemJS. It is a widely used module loader which is based on principles and APIs from the WhatWG Loader specification, modules in HTML and NodeJS. Every bit a matter of fact, Angular-CLI used SystemJS until it moved to Webpack in Beta.12. SystemJS supports both CommonJS and AMD module formats and defines its own System.register format. Boosted explanation nearly the need for SystemJS can be found in this And then answer.

Webpack positions itself as a module bundler for modern JavaScript applications, serving a dissimilar purpose than SystemJS, although when it comes to module loading their functionality somewhat overlap. Webpack bundles all modules into one or several chunks — a bunch of modules packaged in a single file. SystemJS tin can likewise do that but in this respect information technology's much more than limited than Webpack. Where they differ the almost is when information technology comes to loading modules dynamically. While SystemJS can load whatever module dynamically on need during runtime, Webpack tin can only dynamically load chunks divers and created during build time.

Nosotros decided to go here with SystemJS because information technology closely follows the specification, and hopefully, in one case browsers support API for dynamic loading the need for using SystemJS for an Angular application written using ESM modules for the most part will be eliminated. This ways that somewhen, you lot will just need to remove dependency on SystemJS and specify ESM as a typescript output module format, and everything else is supposed to work just fine.

In the following section we volition show the minimal configuration to enable loading Angular application.

Setting up the dependencies

If you utilise angular-cli and run npm install y'all will cease upwardly with the huge number of dependencies. Since in this article we're aiming to testify the minimal setup we'll list and explain the minimal set of dependencies required for Angular. First nosotros demand to create the project by running npm init -y, which creates package.json for us. The -y option accepts the defaults.

And then allow's setup the third-political party dependencies not provided past Angular projection and explain their purpose:

cadre-js

Patches the global object (window) with essential features of ES2015 (ES6). You may substitute it with an alternative polyfill that provides the aforementioned core APIs. When these APIs are implemented past the major browsers, this dependency volition become unnecessary. Essentially, just Reflect polyfill is required in all major browsers (actually, if you use AoT compilation, which is the recommended way for production, you can even skip the Reflect polyfill).

rxjs

Reactive Extensions Library for JavaScript, which includes methods for transforming, composing, and querying streams of data. It is utilized past several parts of the Angular framework, such equally the HTTP and Forms modules. The library provides an Appreciable implementation, which is currently a proposed feature to be included in futurity versions of the JavaScript language.

zone.js

A polyfill for the Zone specification, which has also been proposed for inclusion in the JavaScript language. Zone.js provides the mechanism to hook into asynchronous operations and track outstanding async tasks. Angular does that past creating its ain NgZone which waits until all asynchronous operations similar timers and XHR requests are completed and triggers change detection.

So, install the third party dependencies past running the following command:

          npm i --save core-js zone.js rxjs        

As mentioned higher up, we will besides utilize the SystemJS module loader:

          npm i --save systemjs        

To properly work SystemJS needs some configuration. Permit'southward create a configuration file named systemjs.config.js and add together with the following content:

          Organization.config({
paths: {
'npm:': '/node_modules/'
},
map: {
app: 'dist/app',
'@athwart/core': 'npm:@angular/cadre/bundles/core.umd.js',
'@athwart/common': 'npm:@athwart/common/bundles/mutual.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@athwart/platform-browser-dynamic': 'npm:@athwart/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'core-js': 'npm:cadre-js',
'zone.js': 'npm:zone.js',
'rxjs': 'npm:rxjs',
'tslib': 'npm:tslib/tslib.js'
},
packages: {
'dist/app': {},
'rxjs': {},
'core-js': {},
'zone.js': {}
}
});

Update: for Angular half-dozen, please see the updated config file

The paths and map sections of the config basically define the full path to the source code files for each of the ESM modules in our app. As y'all can see, everything resides inside node_modules, wait for the app code itself, which volition alive inside dist/app.

The packages department lists the meta information for your packages. In this example, we don't ascertain whatsoever metadata, simply adding packages configuration allows us to import files residing in these packages without having to specify the file extension, e.thousand.:

          import { AppComponent } from './app.component';
^^^

This is considering once the packet is listed in the configuration, SystemJS will automatically suspend the .js to any file inside the package (matched by path) by default.

Next, we are ready to ready Athwart dependencies:

@angular/core

Critical run-time parts of the framework needed past every awarding. Includes all metadata decorators, Component, Directive, dependency injection, and the component life-cycle hooks. Contains core functionality component views, DI and change detection.

@angular/compiler

Angular'due south Template Compiler. It reads your templates and tin can convert them to code that makes the application run and render. Typically y'all don't interact with the compiler straight; rather, you use it indirectly via platform-browser-dynamic or the offline template compiler.

@angular/common

Provides the commonly needed services, pipes, and directives such as ngIf and ngFor.

@angular/platform-browser

Contains the functionality to bootstrap the application in a browser. Basically it includes everything DOM and browser related, especially the pieces that assist return into the DOM. May not be required if yous use Angular on the platform other than browser (eastward.thousand. angular-iot).

This bundle likewise includes the bootstrapStatic() method for bootstrapping applications for product builds that pre-compile templates offline.

@athwart/platform-browser-dynamic

Contains implementations for the dynamic bootstrap of the application. Includes providers and a bootstrap method for applications that compile templates on the client (thus, you tin can skip this module if you utilise alee-of-fourth dimension compilation). Use this packet for bootstrapping your awarding during development (equally we do here).

Y'all can also detect the similar description of all Angular packages in the official docs.

To install Angular dependencies run the command (re-create the below into a unmarried line):

          npm i --salvage @angular/core @angular/compiler @angular/common @angular/platform-browser @athwart/platform-browser-dynamic        

Setting up TypeScript

One last step, earlier we get into the actual application code, would exist to ready upward the TypeScript compiler, which will transform our TypeScript code into JavaScript code. While this is not mandatory, using TypeScript is the recommended way to piece of work with Angular.

Nosotros will start by installing TypeScript:

          npm i --salve-dev typescript        

Then, nosotros will create a configuration file, tsconfig.json, with the following configuration:

          {
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"moduleResolution": "node",
"experimentalDecorators": truthful,
"emitDecoratorMetadata": truthful,
"lib": [
"dom",
"es2015"
]
}
}

This is a very basic configuration file, which basically tells the compiler to write the compiled JavaScript files into the dist directory, to convert ESM modules we utilise in TypeScript into the CommonJS module format (ane of the formats natively supported by System.js), and to add decorator support (so we can use @Component, @NgModule, etc). The emitDecoratorMetadata pick is required if you want to specify dependencies using form type instead of @Inject() decorator. This postal service provides a good explanation of the divergence.

For more information on typescript configuration bank check the Configuring TypeScript compiler and the official documentation.

Finally, we will also add together a scripts section to our package.json:

          "scripts": {
"build": "tsc"
},

This will cause npm to run the typescript compiler whenever we write the following command:

          npm run build        

App Skeleton

We got the dependencies set up, and now nosotros are finally set up to first writing code. The commencement thing nosotros will do is to create the alphabetize.html file, which will be the entry point of our awarding. It volition basically load and configure System.js, and and so run the bootstrap code of our app.

Create a file called alphabetize.html with the post-obit content:

          <html>
<caput>
<title>Hello, Angular</championship>
</head>
<body>
<app-main>Loading...</app-primary>
<script src="node_modules/systemjs/dist/organization.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('dist/principal.js').take hold of(office (err) {
console.mistake(err);
});
</script>
</trunk>
</html>

The <app-main> element is the placeholder where our app will be rendered. We load Arrangement.js and its configuration file that nosotros created in a higher place, and then instruct System.js to utilize a load dist/chief.js as the entry point for our application.

After we have the alphabetize file ready, it is time to start creating the actual app code. We will start by creating a very basic Angular component, that says: "Hello, Angular". This volition be an entry point of our application, that is the component that volition exist rendered when the application loads. We will name the file src/app/app.component.ts, following the Angular style guide naming conventions:

          import { Component } from '@angular/core';          @Component({
selector: 'app-primary',
template: '<h1>Hello, {{name}}</h1>'
})
export class AppComponent {
name = 'Angular';
}

Every bit you can see, this is a very basic component — with a simple template, and also a data binding, just to show that Angular actually works in this context. We used app-primary every bit the selector for our component, which is the same as the placeholder element we created in index.html.

Equally you lot probably know we utilize decorators in Athwart to supply information to the framework. In the example to a higher place we apply the @Component decorator and pass a decorator descriptor specifying component selector and template. You lot can learn more nearly decorators in Implementing custom component decorator in Angular.

For the next stride, nosotros would need to create an Angular module that will bootstrap this component. Every bit explained earlier modules are the Angular way of organizing our applications — each module groups related components, directives and services. We volition create the main module of our awarding, in a file called src/app/app.module.ts:

          import { AppComponent } from './app.component';
import { NgModule } from '@angular/cadre';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export grade AppModule {
}

As you can run across, this code is purely declarative: we import the BrowserModule, which is required for rendering in browser surround, and then we declare the component nosotros created in the previous step, and finally set information technology as the bootstrap component — that will exist rendered as soon as this module is bootstrapped.

Now that we accept the module the last piece of the puzzle is creating the code that instructs Athwart to bootstrap our module. Nosotros'll save it equally src/master.ts:

          import 'core-js/es7/reverberate';
import 'zone.js/dist/zone';
import { platformBrowserDynamic }
from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

The commencement two lines import the polyfills that we need — Zone.js and the Reflect polyfill, required by Angular.

The last line is where all the magic happens — we inquire Athwart to bootstrap our module. Since we use platformBrowserDynamic(), angular first invokes the Angular Compiler, which transforms our code into highly optimized code, tuned for high runtime performance. Yous tin learn more than about the Angular compiler and the different optimization strategies in the Athwart Compile Deep Dive web log mail service.

To empathise exactly what these two lines do

          platformBrowserDynamic().bootstrapModule(AppModule);        

read How to manually bootstrap an Angular awarding.

That's it, nosotros are ready to go!

Loading it in the browser

So nosotros have our app ready, but we notwithstanding demand to compile it and serve it before nosotros can load it into the browser. So first, allow's compile it past running:

          npm run build        

For serving the app, we will use a simple http server called live-server. It has built-in live reload feature, and then your awarding volition automatically reload whenever you change 1 of the source file. Install it by running:

          npm i --save-dev live-server        

and so update the scripts department in your bundle.json file:

          "scripts": {
"build": "tsc",
"start": "live-server"
},

And that's information technology! Run the following command to view the app in the browser:

          npm start        

You should see a screen similar to this one:

You lot can also find a minimal project setup, very similar to the one depict here in this repo.

Next Steps

Congratulations, you have merely managed to set an Angular project from scratch. Exciting, isn't information technology?

Of course, at that place is much more to explore and many ways to better our project setup. Here are just a few ideas for what yous could exercise next:

  • Add a "watch" npm script which volition run tsc -w and then you lot don't have to manually run npm build every time you brand a alter to the source code. You tin can as well use the concurrently npm module to run this in parallel with live-server
  • Configure System.js to practise the Typescript transpilation for you during development, and then you lot don't have to run it in the browser
  • Set up server-side rendering (we plan to encompass it in an upcoming web log post)

Summary

Thanks for following along! This is our get-go co-authored blog post, and we hope that you learned something new about Angular. Agreement how Athwart is wired opens upwardly a wide diversity of use-cases which are not yet supported by the current tooling, such every bit build-time rendering and customized development workflows. Nosotros plan to explore these employ cases in subsequent posts.

The key take-away here is that while the Angular CLI does amazing work at simplifying and speeding project setup, wiring the parts yourself is actually not very hard and enables you to take full control of your setup.

Until the next time! 💗

How To Register A Module In Angular Cli,

Source: https://medium.com/angular-in-depth/setting-up-angular-from-scratch-1f518c65d8ab

Posted by: johnsonwisay1979.blogspot.com

0 Response to "How To Register A Module In Angular Cli"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel