Installing and Using Typescript

WE ASSUME THAT NODE.JS IS ALREADY INSTALLED AND THIS ARTICLE IS ABOUT INSTALLING TYPESCRIPT AND USING IT IN A PROJECT WITH SOME IMPORTANT SETTINGS

Before we dive into this it would be beneficial to understand if Typescript is the right language. Check the post here

The article concentrates on Linux flavours such as Ubuntu, CentOS, Redhat etc. The most procedure remains the same. But some basic steps can be taken over to any operating system.


Install Node.JS

To install Node.Js on various Operating Systems please check the official link here.

Create a Project

To Create a Project, Create a new directory with project name. I use jsschools here as my project name

// Create and Change Directory to the Projectmkdir jsschoolscd jsschools
// npm init to initiate a projectnpm init

This create package.json file in the current directory. package.json looks like

// package.json
{  
  "name": "jsschools",  
  "version": "1.0.0",  
  "description": "JSSchools node js project",  
  "main": "index.js",  
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1"  
   },  
  "author": "",  
  "license": "ISC"
}

Install Typescript

Typescript can be installed globally or as a dependency for the project.

To install Typescript globally

// Install typescript globallynpm install -g typescript

The -g options asks the npm to install Typesript globally. This might require admin or root permission depending on the Operating System in use. In Linux like OS it’s always required to run the command with sudo.

// Install Typescript globally with root accesssudo npm install -g typescript

To install Typescript as a project dependency use

// Install Typescript as project dependencynpm install --save-dev typescript

Using Typescript

In the project folder run

// Initialize Typescript in the projecttsc --init

This creates a tsconfig.json file.

// tsconfig.json{  
    "compilerOptions": {    
       "target": "es5",                              
        "module": "commonjs",                         
        "strict": true,                                                      
        "esModuleInterop": true,                            
        "forceConsistentCasingInFileNames": true    
     }
   }

To understand the different compiler options check the documentation here

Your file could be different as the default commented config has been removed here to keep the file short.

Create a new file index.ts. The extension used by typescript program is .ts.

Below is the code in src/index.ts file.

// src/index.tsconst greeting: string = 'Hello World';console.log(greeting)

The variable greeting is a constant which is of string type. Typing is optional (though it can be made mandatory) in Typescript.

Watch this space to learn more about Typescript


Building Typescript

Typescript code cannot be directly executed using Node.Js or in the browser.

Typescript code is built into Javascript code and the resulting Javascript code can be executed.

Typescript code can be compiled directly in may ways. The Easiest way is to run tsc <Typescript file name>

tsc src/index.ts

This creates a index.js file in the current directory.

// index.jsvar greeting = 'test';console.log(greeting);

Note that all the typing information have been removed in Javascript. Typescript only helps in error detection during developmental and Compile phase. It doesn’t add value during the run time as we simply run the resulting javascript code.

This method is suitable if there is a single file. What if we had multiple files in our project. The best approach is to modify the tsconfig.json.

// tsconfig.json{  "compilerOptions": {    "target": "es5",                              "module": "commonjs",                         "strict": true,                               "esModuleInterop": true,                        "forceConsistentCasingInFileNames": true ,    "rootDir": "src",    "outDir": "build"  }}

I have added rootDir and outDir in the tsconfig.jsonrootDir tells the compiler about the location of our .ts files and ourDir tells the compiler about the directory where the compiled .js files are saved

Once tsconfig.json is modified with above configuration, just run tsc with no arguments from project root.

tsc

This creates a build directory and Voila we have our js files.


Running Javascript files

To Run the Javascript files we use the Node.js here ( though browser is another bad option )

node build/index.js

or add the start script in package.json

// package.json{  "name": "jsschools",  "version": "1.0.0",  "description": "JSSchools node js project",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "start": "build/index.js"  },  "author": "",  "license": "ISC"}

and use npm start from root

npm start

Conclusion

Typescript development makes the project free from various silly errors which otherwise are impossible to detect. It aslo helps in making the code standard as Javascript codes can get clumpsy when they grow.

Typescript inclusion in a project is as easy as just spending 10 mins in initial setup.

Leave a Comment