This guide explains how to set up a simple TypeScript project, transpile .ts files to .js, and enable debugging in Visual Studio Code.
-
Initialize the project:
npm init -y
-
Install TypeScript:
npm install typescript --save-dev
-
Create a TypeScript configuration file:
npx tsc --init
-
Modify
tsconfig.json: [see from the project source]- Set the output directory for compiled JavaScript files by updating
"outDir". - Enable debugging by setting
"sourceMap": true.
Example:
{ "compilerOptions": { "outDir": "./build", "sourceMap": true } } - Set the output directory for compiled JavaScript files by updating
Ensure your project has the following structure:
project-root/
├── src/
│ └── main.ts
├── build/
├── package.json
├── tsconfig.json
-
Compile manually:
npx tsc
This will compile all
.tsfiles in thesrcfolder into.jsfiles in thebuildfolder. -
Compile in watch mode:
npx tsc --watch
This will recompile files whenever changes are detected.
-
Add NPM scripts for convenience: Update the
scriptssection inpackage.json:"scripts": { "build": "npx tsc", "watch": "npx tsc --watch" }
You can now run:
npm run build npm run watch
-
Set
sourceMaptotrueintsconfig.json:{ "compilerOptions": { "sourceMap": true } } -
Configure VSCode:
- Open VSCode and navigate to
Run->Add Configuration. - Select
Node.jsas the environment. - This will create a
launch.jsonfile under the.vscodefolder.
- Open VSCode and navigate to
-
Update
launch.json: Example configuration:{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}/build/main.js", "outFiles": ["${workspaceFolder}/build/**/*.js"], "sourceMaps": true } ] } -
Debugging Steps:
- Open the
Run and Debugview in VSCode. - Select the
Launch Programconfiguration. - Set breakpoints in your
.tsfiles. - Start debugging by pressing
F5.
- Open the
By following these steps, you can seamlessly transpile TypeScript to JavaScript and debug TypeScript files in Visual Studio Code.