TypeScript in the Browser via Build Tools
What you'll learn: How to run TypeScript code in web browsers using build tools to convert .ts files into browser-compatible JavaScript.
Why Browsers Can't Run TypeScript Directly
Browsers only understand JavaScript—they have no built-in ability to interpret TypeScript's .ts files. When you write TypeScript for the web, you need a build step that transforms your type-annotated code into plain .js files that browsers can execute.
Think of it like this: browsers speak only JavaScript, but you're writing in TypeScript. You need a translator (a build tool) to convert your TypeScript into the language browsers understand.
The Build Tool Bridge
Build tools like Webpack, Vite, and Parcel (which you've seen mentioned earlier) handle this translation automatically. They:
- Take your
.tssource files - Run them through the TypeScript compiler (
tsc) or a faster alternative - Output browser-ready
.jsfiles - Bundle everything together with your HTML and other assets
For example, when you run vite build or webpack build, these tools detect your TypeScript files, compile them, and produce a dist/ or build/ folder containing only JavaScript that you can deploy to a web server.
Development vs Production
During development, tools like Vite use hot module replacement to recompile TypeScript on-the-fly as you save files. In production builds, they optimize and minify the output JavaScript for faster loading.
Key Takeaway: Browsers cannot execute TypeScript directly—you must use a build tool (bundler) to compile .ts files into .js files before serving them to the web.