"sourceMap"

Generates .js.map source maps, so the debugger shows your TypeScript code instead of the generated JavaScript.

On this page

Example

#
JSON
{
  "compilerOptions": {
    "strict": true,
    "target": "ES2022",
    "module": "ESNext",
    "sourceMap": true,
    "outDir": "./dist"
  },
  "include": ["src"]
}

Definition and usage

#

With sourceMap: true, the compiler writes a .js.map file next to every .js file. It’s a map that connects places in the generated JavaScript to lines and columns of the original .ts file.

Browser developer tools and the debugger in your editor use it to show your TypeScript code: you set breakpoints in the .ts file, and stack traces point to the right lines. A //# sourceMappingURL=… comment appears at the end of the .js file, which the tools use to find the map.

Node.js will use the maps in stack traces when started with the --enable-source-maps flag. The inlineSourceMap option pastes the map directly into the .js file, with no separate file. In applications with a bundler, source maps are usually configured in the bundler itself.

Syntax

#
Syntax
"sourceMap": true

More examples

#
The file src/app.ts
TypeScript
export interface Course {
  title: string
}

export function findCourse(courses: Course[], title: string): Course {
  const course = courses.find((c) => c.title === title)
  if (!course) throw new Error(`Course not found: ${title}`)
  return course
}

findCourse([{ title: 'HTML' }], 'Rust')
A stack trace without and with maps
Terminal
npx tsc
ls dist
# app.js  app.js.map

node dist/app.js
# Error: Course not found: Rust
#     at findCourse (file:///project/dist/app.js:4:15)

node --enable-source-maps dist/app.js
# Error: Course not found: Rust
#     at findCourse (/project/src/app.ts:7:22)

Good practices

#
  • Source maps in production make error analysis easier, but they expose your source code. Many teams send them only to an error monitoring tool, instead of publishing them with the site.
  • When moving compiled files, move the .js.map files along with them. The sourceMappingURL comment points to the map with a relative path.
  • In libraries, also include declarationMap, so that “Go to definition” in the editor leads to the .ts source instead of the .d.ts file.

Related entries

#

Spotted a mistake or missing an example? Write to us.