CodeBlanks Logo Icon CodeBlanks

Source maps

Learn to debug transpiled code with source maps.

What is a source map?

Node.js often runs code transpiled by TypeScript or Babel. The transpiled code's line numbers do not match the original source; error stack traces look meaningless. A source map holds this mapping and shows the debugger the original source.

The node --enable-source-maps file.js flag turns on source map support. Error stacks show the original position alongside the transpiled one: at functionName (source.ts:10:5). This makes it easy to find errors in the original file in TypeScript projects. Source map files usually have the .js.map extension and are produced during compilation. Node.js finds and loads them automatically; no extra config is needed.

Reading stack traces

With source maps enabled, error stacks show two positions: transpiled (dist/file.js:42:7) and original (src/file.ts:10:5). You fix the error by looking at the original position.

Example stack: Error: invalid value\n at calculate (src/calc.ts:10:5)\n at main (src/index.ts:25:3). This shows the error originated at line 10 of calc.ts and was called from line 25 of index.ts. Without a source map the stack would only show dist/calc.js; that file is transpiled and hard to read. Source maps also let you set breakpoints on original lines; DevTools maps them automatically.

Practice Write a script that produces a stack trace

Define function calculate(value) { if (value < 0) throw new Error("Negative value"); return value * 2; }. Call with try { calculate(5); calculate(-1); }. Catch with catch (e) { console.log("Error: " + e.message); }. Add console.log("Done").

Starter code

index.js
// Define the calculate function
// write here

// Call with try
// write here

// Catch
// write here

// Print "Done"
// write here

Sample solution

index.js
function calculate(value) {
  if (value < 0) throw new Error("Negative value");
  return value * 2;
}
try {
  calculate(5);
  calculate(-1);
} catch (e) {
  console.log("Error: " + e.message);
}
console.log("Done");

Expected output

Hata: Negatif değer
Tamamlandı

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the source map flag

Question
node --enable-____-maps dosya.js
Answer
node --enable-source-maps dosya.js

Explanation: The --enable-source-maps flag enables source map support.

2 What does a source map show?

index.js
Error at calculate (src/calc.ts:10:5)
  • Only the compiled file location
  • Only the memory address
  • The run time
  • The location in the original source file Correct answer

Explanation: A source map shows the original source position.

3 Match each concept to its role

Term Meaning
source map Mapping to original source
--enable-source-maps Enables the flag
.js.map Map file extension
stack trace Call stack

All lessons in Intermediate