Thursday, July 27, 2017

Creating a New TypeScript Project in VSCode

I recently switched to using VSCode when writing TypeScript apps because I like the lightweight nature of it. However, this means setting up a lot of things yourself when compared to using an IDE like Visual Studio that does everything for you. Here is a quick outline of the steps I use to set up a new project. There aren't many explanations here, this is just a quick reference.

Create the app

First thing you need to do is create a place to put your app and initialize it. So create a folder with your app name, then inside that folder run from the command line: npm init

This will guide you through creating a package.json file by asking a number of questions. Now you can open the folder in VSCode and start working on your app.

Set up the compiler

Next you'll want to get the TS compiler set up for your project. There is a long article here about how to do it, but here's the gist (I'm assuming you already have the TS compiler installed).

In VSCode create a tsconfig.json file and put the following in it:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true
    },
        "include": [
        "src/**/*", "unittests/**/*"
    ]
}

You'll probably want to put all your TS source files in a separate folder in your project. If you want to configure the compiler to only compile files within certain folders use the include option. In this example I'm only compiling files in the src and unittests folders.

Now configure VSCode's default build task to TS. Select menu item: Tasks => Configure Default Build Task then select the tsc:build option in the dropdown list. This creates a tasks.json file already configured to use TS so there's nothing else to do.

Now you can start writing TS. To compile press Ctrl+Shift+B.

At this point you probably don't want to see all the generated JS files. You can hide them by selecting menu item: File => Preferences => Settings and adding the following.

"files.exclude": {
  "**/*.js": { "when": "$(basename).ts"},
  "**/*.js.map": true,
},

Import JS libraries

If you're using JS libraries like JQuery, Knockout, etc., you can add them to your project using npm. You can use the terminal window inside VSCode to do this. For example, to get knockout.js type the following: npm install --save knockout

This will get the knockout file and put it in the node_modules folder. It also saves the reference to your package.json file as a dependency.

If you want type definition files for your libraries it's also very easy to get using npm. npm install --save @types/knockout

Running your app

A great tool for running web apps is live-server, which you can install from npm. If you name your HTML file index.html it will open it in the browser automatically and any time you make changes it will reload the page.




No comments:

Post a Comment