Item 73: Use Source Maps to Debug TypeScript
要点
- 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!
正文
ts
// 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)
ts
// 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)
}
ts
// 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()