Starting a TypeScript project with Visual Studio Code
Visual Studio Code is a very great IDE for TypeScript. While VS Code is a lightweight source editor, it is very powerful. It supports lots of languages such as C++, C#, Java, Python, PHP, Go, but some of them have a better integration. This is the case for TypeScript. VS Code allows you to write TypeScript code with autocompletion, refactoring, error reporting, quick fixes, automatic build, debugging, etc. In this post, we'll see how to set up your first TypeScript project with VS Code.
If you are not familiar with VS Code, here's a quick description from the documentation:
#Install Visual Studio Code and TypeScript
Install VS Code: https://code.visualstudio.com/
Install NodeJS : https://nodejs.org/
Install TypeScript using the following command line:
Shellnpm install -g typescript
Check TypeScript is installed
Shelltsc --version
#Create a project
Create a new folder that will contain the sources
Create a
tsconfig.json
with the following content (you can use the commandtsc --init
):JSON{ "compilerOptions": { "target": "es5" } }
Create an
src
folderAdd an empty TypeScript file in the
src
folder
The file structure should be like:
MyTypeScriptProject
├── src
│ └── main.ts
└── tsconfig.json
#Compile the project
Open the command palette using CTRL+SHIFT+P, and type "Tasks":
Select "Configure Default Build Task", then select "tsc:watch"
This will create a new file .vscode/tasks.json
with the following content:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"option": "watch",
"problemMatcher": [
"$tsc-watch"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
You can now build your TypeScript files by pressing CTRL+SHIFT+B. After the compilation succeed, you should see a new file main.js
in the explorer:
The task is a watch task, so TypeScript will run automatically when you change a TypeScript file.
#Hide the JavaScript file from the Explorer
After compiling the TypeScript files, you'll have lots of ts and js files in the explorer of VS Code. As you'll never edit the JS files, you can simply hide them in the Explorer.
- Open the settings: File → Preferences → Settings
- Select "Workspace settings" in the right panel
- Add the following json
{
"files.exclude": {
"**/*.js": true
}
}
The workspace settings are saved in .vscode/settings.json
, so this will apply only for the current project.
#Conclusion
You are now ready to use Visual Studio Code for your TypeScript projects
Do you have a question or a suggestion about this post? Contact me!