Skip to content

Instantly share code, notes, and snippets.

@smashdevcode
Forked from kenhowardpdx/tutorial.md
Last active April 11, 2018 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smashdevcode/71d38caf0f8e58a82d8f908aafea8dc4 to your computer and use it in GitHub Desktop.
Save smashdevcode/71d38caf0f8e58a82d8f908aafea8dc4 to your computer and use it in GitHub Desktop.
Node Quick Start Tutorial Using TypeScript

Initial Setup

Download and install VS Code

Download and install Node

Create a Project Folder & Open VS Code

mkdir ts-hello-world
cd ts-hello-world
code .

Create Node Project

npm init -y

Install Dependencies

npm install typescript mocha ts-node @types/node @types/mocha --save-dev

mocha

JS testing library

https://mochajs.org/

ts-node

TypeScript execution environment and REPL for node. Works with typescript@>=2.0.

https://www.npmjs.com/package/ts-node

https://www.bennadel.com/blog/3268-experimenting-with-ts-node-and-using-typescript-in-node-js-on-the-server.htm

Configure Build Script

Add Scripts to NPM

  • Open package.json
  • Find "scripts" section
  • Add "build" script "build": "tsc"

Configure TypeScript

npm run build -- --init

As of npm@2.0.0, you can use custom arguments when executing scripts. The special option -- is used by getopt to delimit the end of the options. npm will pass all the arguments after the -- directly to your script.

This generates a tsconfig.json file in your project root.

We'll need to modify it to generate source maps and output the JavaScript to the /dist folder.

  • Open tsconfig.json
  • Find "inlineSourceMap"
    • Uncomment it and set value to true
  • Find "outDir"
    • Uncomment it and set value to "./dist"

EditorConfig

Add .editorconfig (not required)

  • EditorConfig for VS Code - Visual Studio Marketplace
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = true

Source Files

Add src/HelloWorld.ts

export class HelloWorld {
  public helloWorld() : string {
    return 'Hello World'
  }
}
export default HelloWorld;

Add src/HelloWorld.test.ts

import * as assert from 'assert';
import { HelloWorld } from './HelloWorld';

describe('Hello World test suite', function() {
  it('Can say Hello World', function() {
    const result = new HelloWorld().helloWorld();
    assert.equal(result, 'Hello World', `Should return: Hello World, but returned: ${result}`);
  });
});

Add src/Calc.ts

export class Calc {
  public add(num1: number, num2: number): number {
    return num1 + num2;
  }
  public subtract(num1: number, num2: number): number {
    return num1 - num2;
  }
}
export default Calc;

Add src/Calc.test.ts

import * as assert from 'assert';
import { Calc } from './Calc';

describe('Calc test suite', function() {
  let calc = new Calc();

  it('Can add', function() {
    let result = calc.add(5,5);
    assert.equal(result, 10, `Should return: 10, but returned: ${result}`);
  });

  it('Can subtract', function() {
    let result = calc.subtract(20,10);
    assert.equal(result, 10, `Should return: 10, but returned: ${result}`);
  });
});

Build

  • Press cmd + shift + b
  • Alternatively, run from a terminal:

npm run build

VS Code TS Features

  • Renaming
  • Go to definition
  • Find all references
  • Reference counting
  • Auto imports

Adding Tasks

Add Default Build Task

  • Press cmd + shift + p to open the command palette.
  • Search for "Configure Default Build Task"
  • Select npm: build

Add Test Task

  • Press cmd + shift + p to open the command palette.
  • Search "Configure Default Test Task"
  • Select npm: test

Configure Test Task

  • Open package.json
  • Find "scripts" section
  • Find "test" script
  • Replace with "test": "mocha --require ts-node/register --watch --watch-extensions ts,tsx \"src/**/*.test.{ts,tsx}\"",
  • --require - Loads a module
  • --watch - Watch files for changes
  • --watch-extensions - Additional extensions to monitor with --watch

Run Tests

  • Press cmd + shift + p
  • Search "Run Test Task"
  • Run tests

Debugging

Debug while running your test suite

Open the debug pane by clicking the bug icon on the left side of VS Code. You can also use Command+Shift+D keyboard shortcut.

Click the gear icon. This will open the command palette when a launch.json file is not present. Click Node from the options. We aren't going to use the default configuration. Instead use this script:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Run Mocha Tests",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
            "args": [
                "--no-timeouts",
                "--colors",
                "--require",
                "ts-node/register",
                "${workspaceRoot}/src/**/*.test.{ts,tsx}"
            ],
            "cwd": "${workspaceRoot}",
            "protocol": "inspector"
        }
    ]
}

Now you'll be able to set breakpoints in your code and run your test suite through the debugger built into VS Code. This is helpful because you can inspect your code when tests fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment