Setting Up a New TypeScript Project

It’s easy to work with TypeScript when using a starter project or a tool like the Angular CLI, but what about a simple TypeScript project that would otherwise be just a vanilla JavaScript project? Let’s go over some simple ways to get started.

Dependencies

First, you need TypeScript installed of course. You can decide to have it installed globally on your machine, or locally to your project.

To install globally, run:

$ npm i typescript -g

# or, using Yarn:
$ yarn global add typescript

And to install locally, run:

$ npm i typescript --save-dev

# or, using Yarn:
$ yarn add typescript --dev

Setup

TypeScript comes with two binaries: tsc and tsserver. tsc is the TypeScript compiler and has a command line interface with plenty of available options. To initialize a TypeScript project, simply use the --init flag:

$ tsc --init

If you’re using a version of TypeScript installed locally, you’ll instead want to ensure that you’re running the local version by calling tsc from the local node_modules folder:

$ ./node_modules/.bin/tsc --init

Or, even better, simply using npx to ensure that the local version of tsc is used:

$ npx tsc --init

After running tsc with the --init flag, a tsconfig.json will be added to your project folder with a few sensible defaults and an extensive list of commented-out possible configurations. Here are the starting configurations:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  }
}

Let’s add just two more options to that base configuration:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "outDir": "dist",
    "sourceMap": true
  }
}

With this, the JavaScript files that the TypeScript compiler outputs will be in a dist folder and sourcemaps will be generated.

Compiling

With the tsconfig.json in place, we can start coding our app in TypeScript.

Let’s create an index.ts file in a src folder with this content:

const world = '🗺️';

export function hello(word: string = world): string {
  return `Hello ${world}! `;
}

Now, we can compile by simply running tsc:

$ tsc

# or, for local tsc:
$ npx tsc

And bam, our JavaScript and sourcemap files are created! Here’s the content of the compiled JavaScript:

/dist/index.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var world = '🗺️';
function hello(word) {
    if (word === void 0) { word = world; }
    return "Hello " + world + "! ";
}
exports.hello = hello;
//# sourceMappingURL=index.js.map

Watch mode

Instead of running the TypeScript compiler every time you make a change, you can start the compiler in watch mode instead so that it recompiles every time there are changes to the TypeScript files:

$ tsc -w

# or, for local tsc:
$ npx tsc -w

tslint

Using a linter when coding is a must to quickly know about inconsistencies, syntax errors and omissions. The de facto linter for TypeScript is tslint.

Let’s go ahead and install/configure tslint into our project. Using npm run this command:

# for installing globally:
$ npm i tslint --g

# for installing locally:
$ npm i tslint --save-dev

Or, if you prefer using Yarn:

# global:
$ yarn global add tslint

# or local:
$ yarn add tslint --dev

With tslint installed, we can initialize it using the --init flag:

# if using global tslint:
$ tslint --init

# if using local tslint:
$ npx tslint --init

This will add a tslint.json file to your project with the following default configuration:

tslint.json

{
  "defaultSeverity": "error",
  "extends": [
    "tslint:recommended"
  ],
  "jsRules": {},
  "rules": {},
  "rulesDirectory": []
}

Now, you’ll probably also want to install the tslint extension for your code editor so that you can see linting errors right away when coding. After you’ve done this, you may need to restart your editor.

Using the code from our simple example from above, tslint complains that our quote marks should be double-quotes () and that the file should end with a new line. Say we like to use single quotes and not adding an extra line at the end of files, we can add two rules to our tslint configuration to change this:

tslint.json

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "eofline": false,
        "quotemark": [
            true,
            "single"
        ]
    },
    "rulesDirectory": []
}

Airbnb style-guide for tslint

Adding rules manually is certainly no fun, so often the easiest is to go with a well known and accepted default configuration, and Airbnb’s is one such configuration.

Let’s go ahead and install it in our project:

$ npm install tslint-config-airbnb

# or, using Yarn:
$ yarn add tslint-config-airbnb

And now we can change our tslint config so that it extends the Airbnb config instead:

tslint.json

{
    "defaultSeverity": "error",
    "extends": "tslint-config-airbnb",
    "jsRules": {},
    "rules": {
        "eofline": false
    },
    "rulesDirectory": []
}

Notice how we removed the single quotemark rule, as the Airbnb already has a rule for single quotes.

Making Things Even Easier: Enter gts

Now that we understand how most of the building blocks fit together, we can take a shortcut and avoid having to setup linting and the tsconfig.json file. Google TypeScript Style (gts) is a project to make it even easier to bootstrap a new TypeScript project, avoid bikeshedding, and have opinionated defaults in place.

All you have to do to start a new project is to run this command in a new folder:

$ npx gts init

Make sure you have npm >= 5.3, which comes bundled with npx automatically.

The command will generate everything you need to get started with a tsconfig.json and linting setup. It’ll even generate the project’s package.json file if you don’t have one in place already.

You can now simply install the dependencies:

$ npm install

# or, using Yarn:
$ yarn

gts also adds a few convenient npm scripts to the project’s package.json file. For example, to compile the project you can simply run npm run compile and, to check for linting errors, run npm run check.

To have tslint work with your editor, you’ll still have to manually add a tslint.json file to your project that extends gts’ tslint configuration:

tslint.json

{
  "defaultSeverity": "error",
  "extends": [
    "./node_modules/gts/tslint.json"
  ],
  "jsRules": {},
  "rules": {},
  "rulesDirectory": []
}

gts is still in heavy development and hasn't reached a stable version at the time of this writing, so thread carefully.

🔧 And now you have an easy way to get started with TypeScript! In a future post we'll explore how to throw webpack into the mix.

  Tweet It
✖ Clear

🕵 Search Results

🔎 Searching...