Typescript Foundations / Typescript Tooling

Source maps and debugging

When you write TypeScript, the compiler converts (transpiles) it into JavaScript. This makes debugging a bit tricky, since you're running JS but wrote TS. That’s where source maps help.


✅ What is a Source Map?

A source map is a file that maps the compiled JavaScript code back to the original TypeScript source code. This allows browsers and debuggers (like VS Code or Chrome DevTools) to show the original .ts code while debugging.


🔧 How to Enable Source Maps

You can enable it in tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true
  }
}

When this is enabled, for every .ts file compiled to .js, a corresponding .js.map file is created.


📂 Example Output

For a file app.ts, TypeScript generates:

  • app.js – compiled JavaScript

  • app.js.map – source map file

At the end of app.js, you'll see a comment like:

//# sourceMappingURL=app.js.map

This tells the browser to use the source map for debugging.


🐞 Debugging in the Browser

If you're using tools like Chrome DevTools:

  1. Compile your TypeScript with sourceMap: true.

  2. Open DevTools → Sources.

  3. You’ll see the original .ts files.

  4. You can set breakpoints in TypeScript and debug like it's native code.


🧠 Bonus Tips

  • Use inlineSourceMap: true to embed the source map into the .js file itself. This avoids a separate .map file.

    {
      "compilerOptions": {
        "inlineSourceMap": true
      }
    }
  • Use sourceRoot or mapRoot if your project structure is more complex.


✅ Why It's Useful

  • Debug the original TypeScript source, not the compiled JavaScript.

  • Set breakpoints, inspect variables, and trace errors more easily.

  • Great developer experience in tools like VS Code, WebStorm, and Chrome DevTools.