Tuesday, October 10, 2023

Use of TypeScript Configuration File(tsconfig.json)

 Assume that i have list of ts files in a folder as shown below in the folder

C:\Examples









        
>tsc tsc.cmd methodoveriding --removeComments
>tsc file2 --removeComments
.. | repetition of target and remove comments

Each .ts file, when we compile it will generate a .js file.  In that .js file which has comments in that file. So now I want a common configuration file which should tell do not include comments in the js file.

The solution for this is tsconfig.json file

Now , we will 

 d:\project1
           |
         file1.ts
         file2.ts
         tsconfig.json-->target:"es6"
                         removeComments:true

typescript configuration file will provide instructions to typescript
 compiler to compile the files present in the current folder and sub folders

typescript configuration filename is tsconfig.json

syntax:
 {
   "compilerOptions":{
    "target":"..",
    "removeComments":"..",
    "sourceMap"     :"..",
    "outDir"        :"..",
    "outFile"       :"..",
           ...
                     },
     "files"  :[...], 
     "include":[...],
     "exclude":[...],
        ...
  }


1.target-specify ecma script target version, default is es3
2.removeComments-true | false
                                 true--ts file comments will not be placed into js file, this                                                     will minify[reduce] js file size.
                                 false--.ts files comments will be placed into js file.
3.sourceMap--true |  false
                                 true--map file be generated for debugging.
                                 false--map file will not be generated.
 4.outDir--    specify output directory name to store  |  place js files
 5.outFile--   specify js filename to bundle ts files compiled code.
 6.files--specify filenames to be considered for compilation
 7.include--specify folder names to be considered for compilation.
 8.exclude--specify filenames and folder names to be skipped for compilation

Example

Let us create a new folder.

Go to command window
  C:\>md angulartsconfig

   C:\>cd angulartsconfig

Go to Visual Studio and open the newly created folder.

Click on new file button
    file1.ts
        |
//file1 code
console.log("file1 code");

*click on new file button
    file2.ts
        |
//file2 code
console.log("file2 code");

*click on new file button
    file3.ts
        |
//file3 code
console.log("file3 code");
















click on new file button
   tsconfig.json
       |
{
  "compilerOptions": {
      "target": "ES5",
      "removeComments": true,
      "sourceMap": false,
      "outDir": "dist"
   }
}














Next , let me create a new folder with the Name Demo




Inside Demo folder, let me create another three typescript files
file4.ts, file5.ts, file6.ts

















Now just run 








Now, you can see a new dist folder is been created and the ts files are converted to js files as below. You can also see the same structure is been created. 





















Now, let me open the file1.js , to check if the comments exists or not.




outFile:
-------
The requirement is bundling all the ts files compiled code into single js file bundle.js,

this requires outfile option

*goto tsconfig.json
  {
    
  "compilerOptions": {
      "target": "ES5",
      "removeComments": true,
      "sourceMap": false,
      "outDir": "dist",
      "outFile": "bundle.js"  ===>[add this line]
                 }
 }


















Goto Terminal and Run Now





You will be able to see the bundle.js file Now















files option:
-------------
The requirement is compilation of file3.ts and file6.ts,this requires files option


















Goto Terminal 



Goto bundle.js and see






include and exclude options:
----------------------------
The requirement is compilation of all the files except file6.js[Demo folder],this
requires include and exclude option

Goto tsconfig.json


















Goto Bundle.js and see the output












Note: when we go with include and exclude option file options is not required.
In the above example in the include option we are saying that all the files present in the root folder and Demo folder.

project[-p] option with tsc
---------------------------
This is used to inform typescript configuration filename to tsc ,this is required
 when the typescript configuration filename is other than tsconfig.json

Syntax:
  tsc -p "configfilename"

Now, let us rename the existing tsconfig.json to tsconfig1.json


After that compile, and see you will get an Error. The reason is it will look for tsconfig.json file only. As we have renamed it it will give us an error. Now we need to tell the configuration file name

extends option

This is used to create a new configuration file based on existing configuration
file, this provides reusability.

Requirement is

In my project I have two files, with the name 
login.ts, 
register.ts

Now, I am going to create a new tsconfig5.json file with the below options
tsconfiges5.json-->     target:"es5",
                                 outFile:"es5bundle.js",
                                 removeComments:true,
                                 sourceMap:false

tsconfiges6.json-->    target:"es6"
                         outFile:"es6bundle.js",
                         removeComments:true,
                                sourceMap:false

Here, repetition of remove Comments and source Map options in 2 config files

The solution is creating a base configuration file with common options, this
base configuration file can be inherited [extended]  from other configuration files using extends option

The above one using extends:
       project1
          |
       login.ts
       register.ts
       base.json  ========> "removeComments":true,
                                             "sourceMap":false

      tsconfiges5.json====>    "extends":"./base.json",
                                             "target":"es5",
                                              "outFile":"es5bundle.js"

      tsconfiges6.json====> "extends":"./base.json",
                                              "target":"es6",
                                              "outFile":"es6bundle.js"


tsc -p tsconfiges5.json===>it will generate production bundle[es5bundle.js]
                                           targeting to es5

tsc -p tsconfiges6.json===>it will generate production bundle[es6bundle.js]
                                          targeting to es6








Collections in TypeScript

 Typescript is providing with collections:

 1.Map collection
 2.Weak Map collection
 3.Set collection
 4 Weak set Collection


Map collection:

*Map is a collection of key and value pairs, key should be an unique
*key and value can be of any type

Syntax:
let <mapobject>=new Map();

Methods

 1.Set(key, value)-It will add | modify an element of map collection, it will
                  return map object

    key is not existing-->adding
    key is existing    -->modifying

 2.get(key)        It will return a value based on key
 3.delete(key)    It will delete an element based on key
 4.has(key)        It will verify whether element based on key is present or not, it
                         will return true | false
                        
                        true--existing
                        false--not existing

 5.size               It will return collection count
 6.keys()           It will return keys collection
 7.values()         It will return values collection
 8.entries()        It will return key and value collection


Example






















Output

Map (4) {1 => "angular", 2 => "reactjs", 3 => "nodejs", 4 => "azure"} 

Map (4) {1 => "angular17", 2 => "reactjs", 3 => "nodejs", 4 => "azure"}

false

1

2

3

"angular17"

"reactjs"

"nodejs"

1, "angular17"

2, "reactjs"

3, "nodejs"


WeakMap:

Weak map is a collection of key and value pairs, 

key should be an unique

key should be an object and value can be of any type.

Setting key to null, will remove corresponding element automatically from weak map collection, this will not happen with map collection

Methods[same as Map collection]:
 1.set(key,value)
 2.get(key)
 3.delete(key)

Example:

let weakmap=new WeakMap();
let user1={name:"charan"};//object[key]
let msgs1=["hi","how r u"];//value

let user2:string | null
user2={name:"raju"};
let msgs2=["fine","thank u"];

weakmap.set(user1,msgs1);
weakmap.set(user2,msgs2);
console.log(weakmap.get(user1));
console.log(weakmap.get(user2));

Output

["hi", "how r u"]

["fine", "thank u"]

Set:
----
Set is a collection of unique values, value can be of any type.
Set is similar to an array, but array allows duplicate values, where as set allows unique value

Array will have restricted size, where as set will not have size restriction

Methods:
 1.add(value)--it will add an element into set collection
 2.delete(value)
 3.values()--it will return values collection

Example

let set=new Set();
set.add("hyd").add("bang").add("chennai").add("noida");
console.log(set);
set.add("hyd");//it will not add
console.log(set);
let arr=Array.from(set);//it will create an array based on set
arr.push("hyd");//it will add an element to an array,it will not reflect on set
console.log(arr);
console.log(set);

Output

Set (4) {"hyd", "bang", "chennai", "noida"}

Set (4) {"hyd", "bang", "chennai", "noida"}

["hyd", "bang", "chennai", "noida", "hyd"]

Set (4) {"hyd", "bang", "chennai", "noida"}


Note
-----
Collections are provided with generic to specify particular datatype

   map()[non generic]                map<type,type>()[generic] 

   set()[non generic]                  set<type>() [generic]

   let set1=new Set<number>(); [set can accept only
                                                 unique numbers]

WeakSet:
--------
Weak Set is a collection of unique values, value should be an object

Setting value to null, will remove corresponding element automatically from weak set collection.

Modules,NameSpaces,Exports, Imports in TypeScript

 Module is a collection of variables, functions, classes and interfaces.

 This will be reusable across different other modules with in a project.

Scenario


    <>.ts                                    <>.ts
      |                                            |
 export class c1                       import{c1,c2} from "./module1";
  {..}                                          obj=new c1();
 export class c2                              ..
  {..} 

     |                                                |
  [module1]                                [module2]



                                                       <>.ts
                                                          |
                                               import{c1,c2} from "./module1";
 
                                                          ....
                                                    [module3]

Syntax:

   export namespace <namespacename>
   {
     
        export let <varname>:<type>=value;

        export function <funcname>()
         { .. }

        export class <classname>
         { .. }

       export interface <interfacename>
         { .. }

    }


  ->export members are module public, this will be accessible outside
    module
  ->export members of one module can be accessed | referenced in another
    using "import" keyword.

NameSpace:

namespace is a logical container to group related members.

      eg:
          namespace ns1               obj1=new ns1.c1();                
               |
            class c1                        obj2=new ns2.c1();
             {}
          namespace ns2
               |
           class c1
              {}
    ->namespace is an optional


Now, I have a requirement

   module1.ts                                              module2.ts
       |                                                             |
  namespace inventory   --------------------->importing export members of
  export class category
  export class product                                       module1







Module2.ts

import{inventory} from "./Module1";
let cateobj=new inventory.category("c001","mobiles");
let prodobj=new inventory.product("p001","samsung");
cateobj.display();
prodobj.display();


Output

PS C:\Examples> tsc.cmd Module2.ts PS C:\Examples> node Module2 c001 mobiles p001 samsung

Note: Here Module2.ts compilation will perform all the dependent modules[Module1.ts]
compilation automatically
 
    tsc Module2.ts------>   compilation of Module2.ts and Module1.ts
                                    |
                                Module2.js
                                Module1.js


Note: Namespace naming is optional

Without Namespace



















Output
PS C:\Examples> node Module2      
c001 mobiles
p001 samsung


Working with multiple Modules Examples









Modify the Module2.ts code as below

import{category,product} from "./Module1";
let cateobj=new category("c001","mobiles");
let prodobj=new product("p001","samsung");
cateobj.display();
prodobj.display();
export class emp{}
export class dept{};
export{category,product};


Module3.ts







Debugging in TypeScript

debugging in typescript:
------------------------
Debugging is the process of line by line execution to identify logical errors
 (or) understanding execution flow

Debugging typescript requires 2 things
 1.debugger keyword
        this will stop terminate normal execution and control will be taken into
        debug mode for line by line execution  

 2.map file
       this is a linker file between typescript code and Javascript code, this will execute
       typescript equivalent Javascript code in the background

map file can be generated using sourceMap option with typescript compiler
 syntax:
    tsc <tsfilename> --sourceMap

  

Browser Debug

stringExample.ts 

let link:string ="<a href= 'home.html'>Home </a>";
let year:number=2023
let msg:string =`Next Year  ${year + 1} Card Expires`;
let path:string="\"C:\\Examples\\Images\\Img1.png"

When we run this, it will generate .js file, and we need to use that in the html code.

StringExampleHtml.html

<html>
    <head>
        <title>TS - Basic Concepts</title>
        <script src="stringexample.js"></script>
        <script>
            document.write("path= " + path  + "<br>");  
            document.write("message = " + msg  +"<br>");
            document.write("link = " + link  +"<br>");
        </script>
    </head>
    <body>
        Hello World <br>
    </body>
</html>


Output with Debugger







Property in TypeScripts

Property can be used to set or get private field of a class

Property declaration requires 2 accessors set and get

Syntax:

  public set <propertyname>(para)
  {
     set private field and perform calculation (or) validation
  }

  public get <propertyname>():<type>
  {
       return private field
  }

  Property is a combination of 2 blocks
 1.set block--writting to a property will execute set block
 2.get block--reading a property will execute get block

Example

   Emp class
     |
   sal property[set{da=sal*0.3} and get{..} blocks]
   _sal private field
   _da  private field

  e=new emp();
  e.sal=10000;-->set block execution[da=3000]

  e.sal=e.sal+5000;
          |
        reading[get block execution]
          |
         10000+5000
             |
          15000
        |
     set block exec[da=4500]

Property looks like normal public field, but internal execution will be like
methods.

Property is recommended when you want to perform calculation validation
based on specific private field.


Example















Note:
Accessors are only available when targeting ECMAScript 5 and higher

Output
empno:1 sal:10000 da:3000
empno:1 sal:15000 da:4500

Note:
*target ECMAScript version can be given to tsc using "target[-t]" option
  syntax:
       tsc <tsfilename> -t ecmascript version[es5|es6|..]


Sample way of calling ECMAScript 
*goto terminal
  >tsc propertydemo.ts -t es5
  >node propertydemo

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...