Click here to Skip to main content
15,502,349 members
Articles / Programming Languages / Typescript
Article
Posted 21 Sep 2017

Stats

96K views
4.3K downloads
88 bookmarked

Learn Angular Tutorial

Rate me:
Please Sign up or sign in to vote.
4.90/5 (37 votes)
21 Sep 2017CPOL26 min read
This is Part 1 of an Angular tutorial. In the first part, we will cover Node, TypeScript, Module loaders , bundlers and VS code.
This article teaches you Angular in a step by step manner, but will focus on five labs that will cover the pre-requisites for Angular. This article covers Node (practicing NodeJS, Installing NodeJS, understanding package.json file), TypeScript (practicing Typscript, installing Typescript), VSCode, Module loaders, and Module Bundlers.

Contents

Links to Rest of the Articles

  • In the first part, we look into Node, TypeScript, Module loaders /Bundlers and VS Code
  • In the second article, we create a simple basic Angular application with a screen and we ran through important concepts like components and modules
  • In the third article, we look into implementing SPA and validations
  • In the fourth article, we understand how to make HTTP calls and how to create custom Angular components using Input and Outputs
  • In the fifth part, we cover two labs - one is how to use Jquery with Angular and Lazy routing
  • In the sixth part, we again cover two labs - Pipes and DI using providers

Introduction

Why should we learn Angular? The below stack overflow graph says it all. It's popular, it's hot with lot of job openings. This article teaches you Angular in a step by step manner via 15 great Labs. So if you are here to learn Angular, then you are at the right place and with the right article.

Image 1

In this first article, we will cover five labs. These five labs will cover the pre-requisites for Angular. This article covers Node, TypeScript, VSCode, Module loaders and Module Bundlers.

AngularJS vs Angular. There are two versions of Angular - the old is named as AngularJS and the new one is named as just Angular. So when someone says AngularJS, it means Angular 1.X and when someone says JUST Angular, it's Angular 2/4.

How Does This Article Series Teach You Angular?

The best way to learn Angular or any new technology is by creating a project. So in this step by step series, we will be creating a simple Customer data entry screen project.

This project will have the following features:

  • Application should have the capability of accepting three fields - Customer name, Customer and Customer Amount values.
  • Customer name and Customer codes are compulsory fields and they should be validated.
  • Application will have a “Add” button which help us to post the current customer data to a Server. Once the data is added to the server, it should be displayed on the grid.
  • Application will have a navigation structure wherein we will have logo and company name at the top, navigational link at the left and copyright details at the bottom of the screen.

Image 2 Image 3

So above is the road map for this article. It has three phases:

Theory Phase: In this phase, we will understand what is Angular and why do we need it.

Pre-requisite phase: In this phase, we will see four important things - Node, Typescript, VSCode, Module loaders (SystemJS) and module bundlers (Webpack).

Main learning phase: This is where actual Angular starts. In this, we will be having eight labs and while covering those labs, we will creating the customer data entry screen project as discussed previously.

So do not wait any more. Start LAB by LAB and STEP by STEP.

Should I start from Angular 1, 2 or 4. Angular 1.X and 2.X are very different. So even if you have done Angular 1.X, you have to start afresh from Angular 2.X. Angular 2.X and Angular 4.X are backward compatible so if you are learning Angular 2, you are learning Angular 4 and ahead. So people who are new to Angular, just start from Angular 4. This article teaches Angular 4.

Why Do We Need Angular?

“Angular is an open source JavaScript framework which simplifies binding code between JavaScript objects and HTML UI elements.”

Let us try to understand the above definition with simple sample code.

Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.

TypeScript
function Customer() 
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();

Now let us say in the above customer object we want to bind to an HTML text box called as “TxtCustomerName”. In other words, when we change something in the HTML text box, the customer object should get updated and when something is changed internally in the customer object, the UI should get updated.

HTML
<input type=text id="TxtCustomerName" onchange="UitoObject()"/>

So in order to achieve this communication between UI to object, developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.

TypeScript
function UitoObject() 
{
Cust.CustomerName = $("#TxtCustomerName").val();
}
function ObjecttoUi() 
{
$("#TxtCustomerName").val(Cust.CustomerName);
}

So if we analyze the above code visually, it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.

Image 4

Binding Code

Now the same above code can be written in Angular as shown below. So now, whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated, it also updates the UI.

HTML
<input type=text [(ngModel)]="Customer.CustomerName"/>

In short, if you now analyze the above code visually, you end up with something as shown in the below figure. You have the VIEW which is in HTML, your MODEL objects which are JavaScript functions and the binding code in Angular.

Image 5

Now that binding code has different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View” .
  • Some call it “Presenter” because this logic is nothing but presentation logic.
  • Some term it has “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion, Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

So concluding, the whole goal of Angular is Binding, Binding and Binding.

Lab 1: Practicing NodeJS

So the first JavaScript open source which you should know before learning Angular is NodeJS. In this lab, whatever I am adding is also demonstrated in this Youtube video as well, so feel free to see demonstrative lab.

Theory: What is NodeJS?

NodeJS is an open source JavaScript framework which does two things:

  • It helps you to run JavaScript outside the browser. NodeJS uses the chrome JavaScript engine to execute JavaScript outside the browser so that we can create desktop and server based application using JavaScript.
  • It also acts a central repository from where we can get any JavaScript framework using NPM (Node package manager).

Learn but do not over learn. NodeJS is a big topic by itself. For Angular, we just need to know how to use NPM commands. So we will be limiting ourselves only around how to use NPM. We will not be doing full-fledged node programming. Remember JavaScript is vast. Do not do unnecessary learning because you will lose focus.

Step 1: Installing NodeJs

In order to install NodeJS, goto https://nodejs.org/ and download the latest version and install it.

Image 6 Once you install node, you should see NodeJs command prompt in your program files as shown in the figure.

We can then open the NodeJS command prompt and fire NPM commands inside this command prompt.

In case you are completely new to NodeJS, please see this NodeJS Video which explains NodeJS in more detail.

Step 2: Practicing NPM Install Command

So let’s practice the first command in NPM “npm install”. “npm install” command helps you get the latest version of any JavaScript opensource framework.

For example, if you want to install jquery, you will open node command prompt and type “npm install jquery” and once you press Enter, you should see “jquery” has been installed in your computer.

Image 7
Are you wondering where Jquery has been installed. It has been installed in the same folder where you ran the NPM command.

In that folder, it has created a “node_modules” folder and in that, it has created “jquery” folder where all Jquery had been loaded by “npm”.

Image 8

Step 3: Understanding package.json File

When you work with large projects, you would need a lot of JavaScript frameworks. So in one project, you would probably need jquery, angular, lodash and so on. Doing “npm install” again and again is definitely wasting precious time of your life.

So to load all JavaScript framework references in one go, “npm” team has given a package.json. In this package.json file, you can make an entry to all JavaScript references and load them in one go.

To create package.json file, open the node command prompt and type “npm init”. After “npm init” command, it would ask for package name, version number, project description and so on. Once you fill all the questions, it will create a package.json file in your current folder. Below is how “npm init” command looks like:

Image 9

Once npm init command has been successfully executed, it creates a “package.json” file in the current folder. If you open “package.json” file, it has the following below structure.

Do not overload yourself with all the information, just zoom on the “dependencies” node. This node has all JavaScript dependencies listed out with version number. So in our package.json file, we have all the dependencies listed down.

TypeScript
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "MyClass.js",
  "dependencies": {
    "angular": "^1.6.5",
    "jquery": "^3.2.1",
    "knockout": "^3.4.2",
    "lodash": "~4.17.4"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Wherever “package.json” file is created, you just need to type “npm install” command as shown in the figure.

If you remember in package.json file, we had three JavaScript framework dependencies listed. Those will be installed one after another. You can see in the image that it's stating “added 3 packages”.

Image 10

Learn but do not overlearn. Package.json has lot of configuration. Do not spend your stamina in learning all those. As we do the labs ahead, I will be walking through important ones. So keep moving ahead with the chapters.

Understanding Versioning System in package.json

Most software versions follow semantic versioning. In semantic versioning, versions are divided into three numbers as shown in the image below.

The first number is termed as “major version” , second “minor version” and third “revision”.

Major version: Any increment in major version is an indication that there are breaking changes in the software functionality. It’s very much possible that the old code will not work with these changes and have to be tested properly.

Minor version: This version is incremented when we add new features but the old code still works.

Revision: This version is incremented when we are just doing bug fixes. So there are no new functionalities added, no breaking changes and backward compatible with old code .

Image 11
NPM follows semantic versioning but it also has some more special characters like “^”, “~”, “>” and so on. They dictate how NPM get latest should behave for Major and Minor versions.

For these format, three formats are very primary. Let’s understand each of them.

Exact (1.6.5) , Major/Minor ( ^1.6.5) or Minor(~1.6.5).

Image 12
Exact (1.6.5): This will do a get latest of exact version 1.6.5, not more or not less. If that version is not available, it will throw up an exception.

Major/Minor(^1.6.5): The carrot sign will get minimum 1.6.5 and if there are any higher MINOR / REVISION versions, it will get that. It WILL NEVER GET HIGHER MAJOR VERSIONS. So if 1.6.5 has 1.6.7, it will get that, if it has 1.7.7 it will that, but if it has 2.0 it will NOT get that.

Minimum or lower (~1.6.5): The tilde sign will get HIGHER REVISIONS. For if 1.6.5 has 1.6.7, it will get that, but if it has 1.7.5 it will not be installed, if it has 2.0 it will not be installed.

Image 13

What is package-lock.json File?

As discussed in the previous sections, package.json has “^” and “~” versioning mechanism. Now suppose in your package.json, you have mentioned "jquery": "^3.1.0" and Jquery has a new version “3.2.1”. So in actual, it will install or in other words LOCK DOWN to “3.2.1”.

So in package.json, you will have “^3.1.0” but actually you will be using “3.2.1”. This entry of actual version is present in “package-lock.json”. So package lock files have the EXACT versions which are used in your code.

Below is the image snapshot of both the files.

Image 14

Important NPM Commands

NPM has a huge command list. But here are some very important commands which you will need now and then. As said previously, learn but do not overlearn.

Command Explanation
npm install -g typescript The -g command will install the package globally. In other words, in your computer, when you use this package, it will take the global installation. This should be used only for command lines packages like grunt, typescript, npm and so on.
npm install -save jquery This will install the package and also make a entry into the package.json file. Sometimes, we use a package in our project and forget to update package.json this comes in very handy.

npm view -version jquery

npm view -versions jquery

This first command will show you the latest Jquery version on github and the second one will show all versions in an ascending manner.
npm install -g npm This command updates npm itself. “-g” as discussed previously helps to install npm globally.

Lab 2: Practicing TypeScript

Angular is created using typescript language. So if you are doing development with Angular, typescript is the way to go ahead.

Introduction: Why Do We Need Typescript?

Now JavaScript is a great and WEIRD language. So in JavaScript, if you want to do inheritance, you need to use prototype, it’s not a strongly typed language, there is no polymorphism and so on. So when developers come from C# and Java background, it’s very difficult for them to get acquainted with this weird language. People who come from C# and Java background use OOP features a lot.

So to fill this GAP, the answer is “TypeScript”.

“TypeScript is a sugar-coated Object-oriented programming language over JavaScript.”

Image 15

So in typescript, we can write code using keywords like “class”, “extends”, “interface” and so on.

Internally, typescript will compile (must be right word would be “transpile”) in to pure JavaScript code in terms of functions, closures and IIFE.

Please do watch this 1 hour Training video on TypeScript which explains Typescript in more detail.

Step 1: Installing typescript

So to install typescript, we need to use “npm”. Typescript is a JavaScript open source framework so the best way to get it installed is by using “npm”. So open node command prompt and type “npm install typescript -g”.

The “-g” command says that you can execute typescript command from any folder.

Image 16

Step 2: Compiling a Simple TypeScript to JavaScript

Let’s try to understand how we can compile a TypeScript to JavaScript. So let's create a simple “Customer.ts” file with the following code:

TypeScript
class Customer{
}

Now open nodeJS command prompt and type command ‘tsc “Customer.ts”’. Once you press Enter, it will create “Customer.js” in the same folder.

If you remember “tsc” was registered globally during “npm install” command. So this “tsc” command can be executed in any folder.

Image 17

Below is the JavaScript output from typescript command line utility:

JavaScript
var Customer = (function () {
    function Customer() {
    }
    return Customer;
}());

Many people term this conversion from Typescript to JavaScript as “compiling”. Personally, I feel we should call this process as “transpiling”.

Compiling converts from a higher level languages like C#, Java, C++ to machine language or some intermediate language which cannot be read by humans, while transpiling converts from one higher level language to another higher-level language.

In this, both TypeScript and JavaScript are higher level languages. So let’s term this process as transpiling and let's call typescript as a “transpiler” rather than a compiler.

Step 3: Using tsconfig.json File

The transpiling process of Typescript has lot of advance settings. Below are some options you can pass to tsc command line while compiling:

Options Description
tsc Customer.ts –removecomments While transpiling, the comments will be removed
tsc Customer.ts --target ES5 This will compile using ES5 specifications
tsc Customer.ts --outdir "c:\users\shiv" This will compile to a specific output directory
tsc foo.ts bar.ts –outFile “Single.js” This will compile multiple TS files to single JS file.
tsc Customer.ts -w This command will run typescript continuously in the background and keep looking for changed files. If the file has changed, it will compile that file.

But now let’s think practically, if I want transpile with ES5 specification to a specific directory without comments, the command line would become something as shown below:

TypeScript
tsc Customer.ts --outdir "c:\users\shiv" --target ES5 --removecomments

That’s where tsconfig.json file comes to the rescue. You can put all these configurations in “tsconfig.json” file and then just execute “tsc”.

TypeScript
{
  "compilerOptions": {
    "target": "es5",
    "removeComments": false,
    "outDir": "/Shiv"
  }
}

Learn but do not overlearn. Tsconfig.json has 1000s of properties. Do not spend your stamina in understanding all of them now. Move ahead with the labs. When any new Typescript config comes up, we will look into it.

Lab 3: Practicing VS Code

What is VS Code?

Theoretically, you can do Angular with a simple Notepad. But then, that would be going back to ages of Adam and Eve and reinventing the wheel. So we will need some kind of tools which will help us to type HTML easily, compile typescript and so on.

That’s where VS code is needed. VS code is a free editor provided by Microsoft which will help us with all automation for HTML, JavaScript, Typescript and so on.

So go to https://code.visualstudio.com/download and depending on your operating system, install the appropriate one. For instance, I am having Windows OS so I will be installing the Windows version.

Once you download the setup, it’s a simple setup EXE. Run it and just hit Next, Next and Finish.

You can also watch this VS code tutorial which will help you to understand.

Point Number 1: All Actions Happen in a Folder

In VS code, you put all source code inside a folder. So the first step is to create a folder and point VS code to that folder by clicking on FileOpen and select folder shown in the below figure:

Image 18

Point Number 2: Creating Files and Folders

If you want to create a file or sub folder, you can click on the icons as shown in the figure.

The first icon creates a file and the second icon creates a folder.

Image 19

Point Number 3: Explorer and Open Editors

The explorer part of VS code has two sections, one which shows open editors and the other which shows your folder. You can see the image where open editors are shown. You can click on those cross signs to close the open files.

Image 20

Point Number 4: Reveal in Explorer

If you want to browse to the current folder, you can right click on the folder and click on reveal in explorer.

Image 21

Point Number 5: Integrated Terminal

Typescript, Node these frameworks mostly run through command prompts. So it would be great if we can have integrated command line inside VS code. VS code has something called as integrated terminal, you can open the integrated terminal by clicking on ViewIntegrated terminal.

Once you are inside the integrated terminal, you can fire “npm install” , “tsc” and so on. Below is how the integrated terminal looks like:

Image 22

Point Number 6: Running Multiple Terminals

One of the things we always need is running multiple commands and for that, we need a facility to load multiple terminals.

In VS code, we can load multiple terminals by clicking on the plus sign as shown below. So in one terminal, you can run the webserver and in the other terminal, you can a code review tool.

Image 23

Point Number 7: Changing to Soothing Color Themes

By default, VS code shows black theme which is very good for the health of your eyes. But sometimes to just have more code clarity, you would like to change to some more brighter theme. You can do that by clicking on FilePreferencesColor theme, you would get themes as shown in the below figure:

Image 24

Point Number 8: vs Code Settings

VS code has lot of settings like you can hide unwanted files and only focus on the files you want, change icons settings, change font size and so on. To apply a setting, you need to go to FilePreferencesSettings and you would be shown a figure as shown below.

In this, there are two sections, one which has the preference SAMPLE CODE SNIPPETS and the second section at what level you want to apply these snippets. You can apply snippets at two levels, one at a project workspace level and other at user / computer level.

If you apply at the workspace level, it's only for that project and if you apply at the user level, it will be applied for all projects in that computer.

Image 25

For example, in the user settings, we have pasted the file exclude settings. In this, we have specified we do not want to see the “.JS” and “.Map” files in the workspace.

TypeScript
{
    "workbench.sideBar.location": "left",
    "window.zoomLevel": 2,
    "window.menuBarVisibility": "default",
    "files.exclude": {
    "**/*.js": true,
    "**/*.js.map": true,
    "**/.hg": true,
    "**/CVS": true,
    "**/.DS_Store": true
  },
  "workbench.colorTheme": "Visual Studio Light"
}

Once that setting is applied, you can see the “JS” and “Map” files are not seen.

Image 26

Lab 4: Understanding Module Loaders using SystemJs

You can watch the below videos which demonstrate the concept of Module Loaders and SystemJS practically.

Topic name YouTube URL source
System JS https://www.youtube.com/watch?v=nQGhdoIMKaM
Common JS concept https://www.youtube.com/watch?v=jN4IM5tp1SE

Step 1: TypeScript Modules and Import / Export Keywords

Modular development is one of the important pillars of development. A good software will always have self-contained modules.

So you would like to create separate physical typescript or JavaScript files which will have self-contained code. Then you would like have to some kind of reference mechanism by which modules can be referred between those physical files.

In typescript, we do this by using “import” and “export” keywords.

So the modules which need to be exposed should have the “export” keyword while modules which want to import the exported modules should have “import” keyword.

Image 27
For instance, let’s say we have two typescript files “Customer.ts” and “Dal.ts”. Let’s assume “Customer.ts” is using “Dal.ts”.

So “Dal.ts” will use export to expose his modules while “Customer.ts” will use to import to get the exported module.

Image 28

So in “Dal.ts”, the classes which you want to export should be marked as “exported” as shown in the below code. If you do not mark it exported, it cannot be imported.

TypeScript
export class Dal{
    Add(){
        alert("Dal add called");
    }
}

Now in the “Customer.ts” we use “import” to call the exported class from the “Dal.ts”.

TypeScript
import {Dal} from "./Dal "
export class Customer{
    Add(){
       var dal = new Dal();
       dal.Add();
       
    }
}

So in short, you use export and import to do modular development in Typescript. But now, how does this “TRANSPILE” to JavaScript code that we will see in the next section. At the end of the day, all these modules are transpiled to JavaScript so let's understand how that works under the hood.

Step 2: Module Formats in JavaScript CommonJS, AMD, ES6

Let’s first define this word “Module” formats. We talked about modules in the previous section. Module formats define the JavaScript syntaxes of how the module should be exported and imported.

In the JavaScript world, there are two ways of defining module formats - Unofficial way and Official way. So prior to ES6, there was no official way so some of the unofficial viral ways of defining module formats are CommonJs, AMD, UMD and so on. The official way is only and only one ES6.

For instance, below is the format of commonJS. In commonJS, the module which is exported is defined in “exports” variables and to import, we need to use “require” keyword.

You can see below is the JS output where the dal is exported using “exports” variable.

TypeScript
Object.defineProperty(exports, "__esModule", { value: true });
var Dal = (function () {
    function Dal() {
    }
    Dal.prototype.Add = function () {
        alert("Dal add called");
    };
    return Dal;
}());
exports.Dal = Dal;

Below is the code for “Customer.js” which uses “require” to load “Dal.js”.

TypeScript
Object.defineProperty(exports, "__esModule", { value: true });
var Dal_js_1 = require("./Dal.js");
var Customer = (function () {
    function Customer() {
    }
    Customer.prototype.Add = function () {
        var dal = new Dal_js_1.Dal();
        dal.Add();
    };
    return Customer;
}());
exports.Customer = Customer;

So now, this is a commonJS format in the same way we have other formats as well. For example, below is “amd” module format.

In this, we export the classes in the “export” variable and use “define” to import. Below is the code of “define”. We are not pasting of “export” as it's the same like commonJS.

TypeScript
define(["require", "exports", "./Dal.js", 
"./Validation.js"], function (require, exports, Dal_js_1, Validation_js_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Customer = (function () {
        function Customer() {
        }
        Customer.prototype.Add = function () {
            var val = new Validation_js_1.Validation();
            var dal = new Dal_js_1.Dal();
            dal.Add();
        };
        return Customer;
    }());
    exports.Customer = Customer;
});

In “ES6” module format to expose the class, we need to “export” keywords and to consume, we need to use “import”.

TypeScript
import { Dal } from "./Dal.js";
import { Validation } from "./Validation.js";
var Customer = (function () {
    function Customer() {
    }
    Customer.prototype.Add = function () {
        var val = new Validation();
        var dal = new Dal();
        dal.Add();
    };
    return Customer;
}());
export { Customer };
TypeScript
var Dal = (function () {
    function Dal() {
    }
    Dal.prototype.Add = function () {
        alert("Dal add called");
    };
    return Dal;
}());
export { Dal };

So in simple words “amd” ,”commonJS” and “ES6” define how modules will communicate with each other. Concluding ES6 uses “import / export” , amd uses “define/export” and commonJs uses “require/export”.

Image 29

All these module formats can be generated with simply an option change in typescript config file.

So in “tsconfig.json”, we can set in “module” which module format we want.

Image 30

Step 3: Calling JavaScript Module Loaders in HTML UI

Now when we try to load JavaScript functions which are using module formats like AMD, CommonJS or ES6, it’s not so easy. For example, in the below code in HTML UI, we have loaded “Dal.js” and “Customer”.js”. This example has been demonstrated in the previous lab and is having “CommonJS” enabled.

Also, we have put the sequence properly, first we have added reference of “Dal.js” and then “Customer.js” because “Customer.js” is dependent on “Dal.js”.

But when we try to create “Customer” object and try to call “Add”, it does not work.

HTML
<script src="Dal.js"></script>
<script src="Customer.js"></script>
    <script>
       var cust = new Customer();
       cust.Add();
    </script>

We end up with an error below stating that “exports” is not understood. That makes sense because browser does not know any keywords like “exports” and “require” as it's not standard JavaScript.

The second problem is even if this code had worked, I would still have ordering problems for large number of references. Let's say we have 15 modules which are referencing using module formats. We would end with spending half-life arranging those sequences in HTML file. It would be great if we can just point to “Customer.js” and automatically using “exports” and “imports” the references is identified and “Address.js” is loaded.

Image 31

That’s where we need JavaScript module loaders. Some examples of module loaders are SystemJS, WebPack and so on.

So if we are using module loaders, we just need to point to the first JS file and automatically using the “import/require/define” and “exports”, it will get references of all the dependent JS files and load them accordingly.

Image 32

Let's demonstrate a module using “SystemJS”. So first go to Node command prompt and install “systemjs”.

TypeScript
npm install systemjs

So in the HTML UI, we need to tell “system.js” which is the first JS file to be loaded. You can see in the below code we are saying “SystemJS.import” load “Customer.js” as the first file.

HTML
<script src="system.js"></script>
    <script>
    
        SystemJS.import('./Customer.js')
        .then(function(module){
                var cust = new module.Customer();
                cust.Add();
        }).catch(function (err)
        { console.error(err); });;
    </script>

Once the file has been loaded in the then function, we get the modules. We can then refer to the module variable and create object of “Customer” function.

If you watch the network tab of Chrome browser, you can see first “system.js” loads “Customer.js” and then also loads its reference that is “Dal.js”.

Image 33

Lab 5: Understanding Module Bundlers using WebPack

Introduction: Runtime vs Compile time – Webpack Module Bundler

In the previous Lab 4, systemJS was doing everything at runtime. So in the browser, it first loads “Customer.js” then “Address.js” and so on. If you have lot of dependencies, you would end up with lot of requests.

At the side is a simple image from an enterprise project where we have 342 JavaScript file requests to load the site.

Now that’s a big number and with so many requests, your application performance will come down a lot.

Image 34

If we can create a SINGLE BUNDLE during the compile time itself, that would be a great performance booster.

That’s where webpack (https://webpack.js.org/) comes to use. Webpack is a module bundler.

It takes the first JS file uses module definitions like commonjs / AMD / UMD, etc. and figures out the references and generates one Single JS file DURING COMPILE TIME. You can take this one single bundle JS and put in your web page.

Image 35

So let’s try to understand the basics of how Webpack works.

Step 1: Install WebPack

So the first step is to install webpack. So open the node command prompt and type the below NPM command. Please see we have used “-g” the global flag.

TypeScript
npm install -g webpack

Step 2: Generate a Single Bundle

We take the same code which we have used in “Lab 4”. In lab 4, if you see, we have “Customer.js” calling “Address.js”. So the first JavaScript file is “Customer.js”. We just need to give the first JS file name in the webpack command the final bundle file name. You can also see there is “—output-library” flag parameter. Webpack will expose “CustomerLibrary” component to us from where we can access the “Customer” class in the UI.

TypeScript
webpack "Customer.js" "Bundle.js" --output-library='CustomerLibrary'

Step 3: Calling the JavaScript Class in the Webpage

So now that we have a single bundle, we can just load the JS file in the webpage and access the classes via the “CustomerLibrary”. Remember this “CustomerLibrary” is coming from command line, please revisit step 2 again for details.

HTML
<script src="Bundle.js"></script>
    <script>
        var x = new CustomerLibrary.Customer();
        x.Add();
    </script>

If you now see the network tab, you will see now only one single file “Bundle.js” as compared to multiple files.

Image 36

SystemJS and WebPack. When we learn Angular, we will first use SystemJS and then in one of the labs, we will see how Webpack helps us.

So now that we have completed all the prerequisites, it’s time to start getting into Angular. So from Lab 6, the actual Angular starts.

What's for the Next Article?

So now that we have completed all the prerequisites, it’s time to start getting into Angular. So from Lab 6, the actual Angular starts. To read Next Lab of the "Learn Angular" tutorial, start from here.

For further reading, do watch the below interview preparation videos and step by step video series.

History

  • 21st September, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
GeneralGood article Pin
rammanusani26-Mar-19 8:52
rammanusani26-Mar-19 8:52 
QuestionGreat Tutorial Pin
Member 1415449025-Feb-19 10:56
Member 1415449025-Feb-19 10:56 
QuestionsystemJS and webpack - didn't work for me Pin
Member 1378429611-Oct-18 13:18
Member 1378429611-Oct-18 13:18 
QuestionLearn MEAN Stack Tutorial From Scratch Pin
KrunalLathiya17-Jun-18 9:38
KrunalLathiya17-Jun-18 9:38 
Questionwebpage not opening after starting http-server Pin
Member 122873378-Jan-18 1:17
Member 122873378-Jan-18 1:17 
AnswerRe: webpage not opening after starting http-server Pin
Shivprasad koirala8-Jan-18 14:26
Shivprasad koirala8-Jan-18 14:26 
GeneralRe: webpage not opening after starting http-server Pin
Member 122873378-Jan-18 21:29
Member 122873378-Jan-18 21:29 
GeneralRe: webpage not opening after starting http-server Pin
Shivprasad koirala8-Jan-18 21:45
Shivprasad koirala8-Jan-18 21:45 
GeneralRe: webpage not opening after starting http-server Pin
Member 122873379-Jan-18 21:05
Member 122873379-Jan-18 21:05 
GeneralRe: webpage not opening after starting http-server Pin
Shivprasad koirala12-Jan-18 19:50
Shivprasad koirala12-Jan-18 19:50 
SuggestionNeed a Angular 2 Grid for Production (Modified) Pin
amarjitsaha24-Nov-17 20:42
amarjitsaha24-Nov-17 20:42 
Question'Download Learn Angular 100 Page Ebook in RAR format 3.5 MB' this file not found? Pin
amarjitsaha8-Nov-17 18:50
amarjitsaha8-Nov-17 18:50 
AnswerRe: 'Download Learn Angular 100 Page Ebook in RAR format 3.5 MB' this file not found? Pin
Shivprasad koirala8-Nov-17 19:33
Shivprasad koirala8-Nov-17 19:33 
SuggestionNot Angular 4 :-( Pin
German150326-Oct-17 7:14
German150326-Oct-17 7:14 
GeneralRe: Not Angular 4 :-( Pin
Shivprasad koirala26-Oct-17 7:30
Shivprasad koirala26-Oct-17 7:30 
QuestionNice Tutorial Pin
Nageswar22-Oct-17 19:55
Nageswar22-Oct-17 19:55 
GeneralMy vote of 5 Pin
Mahsa Hassankashi15-Oct-17 7:47
Mahsa Hassankashi15-Oct-17 7:47 
PraiseMy vote of 5 Pin
Muhammad Shahid Farooq14-Oct-17 20:24
professionalMuhammad Shahid Farooq14-Oct-17 20:24 
Questionnice one sir Pin
Pradeep Shet25-Sep-17 20:31
Pradeep Shet25-Sep-17 20:31 
GeneralAfter a long time Pin
Gaurav Aroraa25-Sep-17 2:20
professionalGaurav Aroraa25-Sep-17 2:20 
There is no doubt that it is a great article. After a long time, I am seeing your article, I hope you will write and guide us in future too.
Gaurav Arora
http://gaurav-arora.com

QuestionClassical piece Pin
fardenhailer22-Sep-17 1:09
fardenhailer22-Sep-17 1:09 
GeneralMy vote of 5 Pin
san2debug21-Sep-17 21:46
professionalsan2debug21-Sep-17 21:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.