"sourceMap"
Generates .js.map source maps, so the debugger shows your TypeScript code instead of the generated JavaScript.
Example
#{
"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
#"sourceMap": trueMore examples
#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')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.mapfiles along with them. ThesourceMappingURLcomment points to the map with a relative path. - In libraries, also include
declarationMap, so that “Go to definition” in the editor leads to the.tssource instead of the.d.tsfile.
Related entries
#- "outDir" and "rootDir"The folder where compiled code goes, and the folder of the sources.
- "declaration"Generates .d.ts files with types next to the compiled JavaScript.
- "target"The JavaScript version the compiler turns your code into.
- "module"The module format of the generated code and how imports are understood.
Spotted a mistake or missing an example? Write to us.