One thing that you might have noticed while we were using the debugging in the web browser before is that we only had access to the JavaScript code (as opposed to the TypeScript code when debugging with VS Code directly). In our case, with TodoIt, it is okay because the program is very simple, and so it remains intuitive. But in larger applications, this will simply not be usable.
This is why a feature called source maps is really, really valuable. Source maps are mapping files that create the link between lines in the JavaScript sources and the corresponding ones in the original source code (TypeScript source code, in our case).
Source maps can either be stored in the JavaScript files themselves, in which case, they are called inline source maps or in the separate (that is, external) .map files.
We won't dive much more into the details of how source maps work, but you should simply know that web browsers and their debuggers will automatically detect and load source maps if they're available or reachable. You can check out the following links if you want to know more about source maps:
- https://www.html5rocks.com/en/tutorials/developertools/sourcemaps
- https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map
TypeScript supports generating source maps easily (whether inline or external).
In order to enable the generation of source maps in TypeScript, edit the tsconfig.json file and add the "sourceMap": true, option.
Once done, you should restart the compiler so that you can see a new file: todo-it.js.map.
If you now reload the page in your web browser and check out the Console tab, you'll see that the.ts files are mentioned:
From now on, you can define breakpoints in the original source code, which, as you'll see in later chapters, will become really useful as we build more complex applications:
If you look at the generated todo-it.js file, you'll notice this at the end: //# sourceMappingURL=todo-it.js.map.
This is what tells the web browsers where to find the source map file.
For the sake of completeness, you should also know that sourceMap is not the only option that TypeScript supports. You can also configure the compiler to generate inline source maps using the inlineSourceMap option.
You can also force TypeScript to include the original sources in the source map files. This can be useful for cases where the original source files are not readily available or when your application or build configuration becomes too complex. Refer to the compiler options for more information: https://www.typescriptlang.org/docs/handbook/compiler-options.html.