Blog>
Snippets

Source Maps with TypeScript Compilation

Explain how to generate source maps while compiling TypeScript files to JavaScript to aid in debugging the original TypeScript source.
// tsconfig.json
{
  "compilerOptions": {
    "sourceMap": true
    // other compiler options go here
  }
}
Create or update a tsconfig.json file in the root of your TypeScript project and set the 'sourceMap' option to true. This instructs the TypeScript compiler to generate source maps alongside the compiled JavaScript files.
// Compile TypeScript to JavaScript with source maps using the command line
// Run the TypeScript compiler (tsc command) with the --sourceMap flag if tsconfig.json is not used

// Install TypeScript globally if not already installed
// npm install -g typescript

// Compile with source maps
// tsc --sourceMap example.ts
Shows how to compile TypeScript files to JavaScript with source maps from the command line. If you're not using a tsconfig.json file, you can pass the --sourceMap flag directly to the tsc command.
/* example.ts */
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return 'Hello, ' + this.greeting;
  }
}

let greeter = new Greeter('world');
console.log(greeter.greet());
An example TypeScript file (example.ts) showing a simple class. When compiled with source maps enabled, you will be able to debug this TypeScript file directly in tools that support source maps, like Chrome Developer Tools or Visual Studio Code.