How to Setup TypeScript using NPM and Visual Studio Code?

Rawat Digamber /  Read Time: 7 minutes

TypeScript Setup

Introduction to TypeScript?

First and foremost, TypeScript is a modern day programming language. We use this programming language for large-scale JavaScript application development. We can refer to it as a typed superset of JavaScript.

The best thing about TypeScript is that you will gain access to features from recent versions of ECMAScript as well. And you may use features beyond the scope of that as well. When you compile TypeScript, you will be able to produce a version of JavaScript which is safe across all platforms.

Click here to read more about TypeScript

1. Prerequisite

Before we kick start TypeScript project, you must set up Node JS environment in your system. If you don’t have Node JS setup then follow the given link to set up Node JS development environment in your system.

Once you are done setting up Node JS make sure it is working fine by typing the below command

npm
Digambers-MacBook-Pro:typescript-project digambersingh$ npm

Usage: npm <command>

where <command> is one of:
    access, adduser, audit, bin, bugs, c, cache, ci, cit,
    completion, config, create, ddp, dedupe, deprecate,
    dist-tag, docs, doctor, edit, explore, get, help,
    help-search, hook, i, init, install, install-test, it, link,
    list, ln, login, logout, ls, outdated, owner, pack, ping,
    prefix, profile, prune, publish, rb, rebuild, repo, restart,
    root, run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, team, test, token, tst, un,
    uninstall, unpublish, unstar, up, update, v, version, view,
    whoami

npm <command> -h  quick help on <command>
npm -l            display full usage info
npm help <term>   search for help on <term>
npm help npm      involved overview

Specify configs in the ini-formatted file:
    /Users/digambersingh/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@6.4.1 /usr/local/lib/node_modules/npm
Digambers-MacBook-Pro:typescript-project digambersingh$

2. Install Visual Studio Code

I am going to use visual studio code editor to work on TypeScript in our project.

Click here to install visual studio code.

3. Setup TypeScript using NPM

Once you are done with the installation of visual studio code, you need to create a folder which is easy to access. You can give whatever name that you find fitting. I have given the name typescript-project. Now you need to open this file in visual studio code.

You need to create two new files named index.html and app.ts in the TypeScript project folder.

Open the index.html and just add a regular HTML5 boilerplate. You need to make
sure that it has a script tag that appears right before the closing body tag.

index.html

<!DOCTYPE html>

<head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>TypeScript Test Setup</title>
   <meta name="description" content="">
   <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
   <H1>Hello World</H1>
   <script src="app.js"></script>
</body>

</html>

The script tag points to app.js. However, app.js is non-existent at this point. It will get created as soon as we compile the TypeScript.

Build TypeScript Package Manager

When it comes to projects developed in TypeScript, we can take the help of a package manager like NPM. NPM helps us in several ways. First and foremost, you will be able to execute the project in a virtual environment supported by the lite server. It also helps turn the compilation of TypeScript to JavaScript into an automated process. Last but not least, NPM helps us to keep a tab on dependencies.

Open TypeScript terminal within VS code, press shift + cmd + ‘ inside VS Code. Run the below command.

npm init

You will have to input the name of the project before everything else. You may refer to the code below to see the defaults. You don’t need to worry about the defaults at all. You will have to fill up a couple of details including the description and the author. You will also have to input the entry point to your primary JS file.

Here, in this case, app.js is our entry point.

Digambers-MacBook-Pro:typescript-project digambersingh$ npm

Usage: npm <command>

where <command> is one of:
access, adduser, audit, bin, bugs, c, cache, ci, cit,
completion, config, create, ddp, dedupe, deprecate,
dist-tag, docs, doctor, edit, explore, get, help,
help-search, hook, i, init, install, install-test, it, link,
Digambers-MacBook-Pro:typescript-project digambersingh$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (typescript-project)
version: (1.0.0)
description: A basic TypeScript test project.
entry point: (index.js) app.js
test command: test type
git repository:
keywords:
author: Digamebr Singh
license: (ISC)
About to write to /Users/digambersingh/Documents/Open Source/typescript-project/package.json:

{
"name": "typescript-project",
"version": "1.0.0",
"description": "A basic TypeScript test project.",
"main": "app.js",
"scripts": {
"test": "test type"
},
"author": "Digamebr Singh",
"license": "ISC"
}

Is this OK? (yes)

Once you are done with all the key setup parameters, you will be intimated that you are all set to make some changes to package.json. If everything looks fine, press enter once again. You will be able to see the package.json file in VS Code.

{
"name": "typescript-project",
"version": "1.0.0",
"description": "A basic TypeScript test project.",
"main": "app.js",
"scripts": {
"test": "test type"
},
"author": "Digamebr Singh",
"license": "ISC"
}

4. Testing the Package

In order to see if the package is working or not, you need to enter the below command in the terminal.

npm test

You will be greeted with a text message if the testing has been successful.

Digambers-MacBook-Pro:typescript-project digambersingh$ npm test

> typescript-project@1.0.0 test /Users/digambersingh/Documents/Open Source/typescript-project
> test type

5. Adding Dependencies

We have just initialized the basic package for the project. It’s time for us to add some dependencies. And it is referred to as dev dependencies. As far as packages are concerned, there are two types of dependencies. The first type is used in development as in TypeScript. The second type is used production as in jQuery.

We are going to install the following dependencies as dev dependencies:

Concurrently

As it is evident in the name, you are able to run multiple
commands concurrently.

Typescript

In order to start a TypeScript project, you need this.

Lite-server

We are referring to a development only node server here, and it is lightweight in nature. When you alter something in JavaScript or HTML, it refreshes itself. And the changes made to the CSS will be injected via sockets.

We use the below command to install an NPM package.

npm install <package-name>

If you wish to install more than one NPM packages at a time, you achieve the same by separating the packages with space. You need to run the following command to install dev dependencies.

npm install concurrently typescript lite-server

Your package.json file will be updated automatically.

Yes, we have made some good progress as far as our project is concerned. But TypeScript compilation will not happen just yet. We are in need of a tsconfig.json file for the same. We also need to come up with a few extra commands for the project.

We need to run the given below command before we try to configure the scripts. First, you will be greeted by a “Successfully created a tsconfig.json file” message. Now when you open the VS Code you will be able to spot the tsconfig.json file.

tsc --init
Digambers-MacBook-Pro:typescript-project digambersingh$ tsc --init
message TS6071: Successfully created a tsconfig.json file.

6. Setting up the scripts

We have test command in the possession of our script object. When we utilize the npm test, the test command provides output. But we are going to add some additional commands that define our lite-server, TypeScript Compiler Watcher. And a start command will concurrently run several things and update the lite-server in real-time as well. As a result, the development process becomes so much easier.

So let’s take a look at the latest package.json file with script commands.

{
  "name": "typescript-project",
  "version": "1.0.0",
  "description": "A basic TypeScript test project.",
  "main": "app.js",
  "scripts": {  // Defined the custom properties in scripts object
    "test": "test type",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrently \"npm run tsc:w\" \"npm run lite\" "
  },
  "author": "Digamebr Singh",
  "license": "ISC",
  "dependencies": {
    "concurrently": "^4.0.1",
    "lite-server": "^2.4.0",
    "typescript": "^3.1.6"
  }
}

In the scripts object, we have defined the compiler and server as follows.

  • “lite”:”lite-server”Lite server
  • “tsc”:”tsc”TypeScript compiler
  • “Tsc:w”:”tsc-w”TypeScript in watch mode

We have also defined our stand command as well.

7. TypeScript Compiler in Watch Mode

Concurrently has application at this stage. The start command will take the responsibility of concurrently running lite server and TypeScript Compiler in watch mode. Once after saving the package.json, you need to start the project. And it is the final, step. Enter below command in the terminal. The start command exists in the script object will be initiated.

npm start

You will be able to see the Watching files if you haven’t made any errors in the setup. And Chrome should have already launched the project in watch mode. And all the TypeScript files will be compiled producing JavaScript output. All of a sudden you will notice the existence of an app.js file which wasn’t there before. The compiler has generated it while generating the JavaScript output.

[0] Starting compilation in watch mode...
[1] [Browsersync] Access URLs:
[1]  --------------------------------------
[1]        Local: http://localhost:3000
[1]     External: http://192.168.0.102:3000
[1]  --------------------------------------
[1]           UI: http://localhost:3001
[1]  UI External: http://localhost:3001
[1]  --------------------------------------
[1] [Browsersync] Serving files from: ./
[1] [Browsersync] Watching files...
[1] 18.11.05 14:35:24 200 GET /index.html
[1] 18.11.05 14:35:25 404 GET /favicon.ico
[0]
[0] 14:35:25 - Found 0 errors. Watching for file changes.
[1] [Browsersync] Reloading Browsers... (buffered 2 events)
[1] [Browsersync] Reloading Browsers... (buffered 2 events)
[1] [Browsersync] Reloading Browsers...
[1] 18.11.05 14:36:03 200 GET /index.html
[1] 18.11.05 14:36:03 200 GET /app.js

Now we are going to make some changes in app.ts. And this should trigger some action in the terminal. You will see the lite server and the TypeScript Compiler being part of the action.

At this point onwards, whenever we alter app.ts and save it, the compiler get into action as it will convert the TypeScript into JavaScript. You can see it in app.js. Same can be witnessed in the updates happening in the lite server as well.

NPM is really convenient. For instance, once you have setup package.json, you can copy the package. And then you can run the command npm install – it will initiate the installation of all the dependencies. Now run npm start, you already have the project setup ready. You are all set to write your code! However, you should initialize tsconfig with
tsc –init before you attempt that.

Written by Digamber

I am passionate about solving real-world problems through algorithms and functional design. I create digital products that make the user’s life easy using the latest programming languages and frameworks. e.g Angular 2+, Firebase Real-time Database, JavaScript, TypeScript, RxJS, Bootstrap, HTML5, CSS3, WordPress etc...