Item 73: Use Source Maps to Debug TypeScript
May 10, 2024 ยท View on GitHub
Things to Remember
- Don't debug generated JavaScript. Use source maps to debug your TypeScript code at runtime.
- Make sure that your source maps are mapped all the way through to the code that you run.
- Know how to debug Node.js code written in TypeScript.
- Depending on your settings, your source maps might contain an inline copy of your original code. Don't publish them unless you know what you're doing!
Code Samples
// index.ts
function addCounter(el: HTMLElement) {
let clickCount = 0;
const button = document.createElement('button');
button.textContent = 'Click me';
button.addEventListener('click', () => {
clickCount++;
button.textContent = `Click me (${clickCount})`;
});
el.appendChild(button);
}
addCounter(document.body);
// index.ts
function addCounter(el: HTMLElement) {
let clickCount = 0;
const triviaEl = document.createElement('p');
const button = document.createElement('button');
button.textContent = 'Click me';
button.addEventListener('click', async () => {
clickCount++;
const response = await fetch(`http://numbersapi.com/${clickCount}`);
const trivia = await response.text();
triviaEl.textContent = trivia;
button.textContent = `Click me (${clickCount})`;
});
el.appendChild(triviaEl);
el.appendChild(button);
}
// bedtime.ts
async function sleep(ms: number) {
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log('Good night!');
await sleep(1000);
console.log('Morning already!?');
}
main();