Live-server无法运行TypeScript?新手TS使用遇VS Code扩展运行报错
Hey there! Let's break down why Live Server is throwing errors with your TypeScript code—this is such a common hurdle when switching from vanilla JS, so don't stress, we'll get it sorted.
Why This Happens
The key thing to remember: browsers don't understand TypeScript natively. Live Server works great with JS because browsers can parse .js files directly, but .ts files need to be compiled into plain JavaScript first. When you try to run a .ts file directly via Live Server, the browser has no clue what to do with it, hence the errors.
2 Simple Solutions to Get Your TS Code Running
Option 1: Manual Compilation + Live Server (Great for Quick Testing)
This is perfect if you want to stick with Live Server while learning the basics of TS compilation:
- First, make sure TypeScript is installed globally on your machine:
npm install -g typescript - Next, set up a
tsconfig.json(TypeScript's configuration file) in your project root. Run this command to generate a default config:
Open the generatedtsc --inittsconfig.jsonand tweak a couple key settings for convenience:- Set
"outDir": "./dist"(this tells TS to put compiled JS files in adistfolder) - Set
"rootDir": "./src"(keep your raw TS files in asrcfolder to stay organized)
- Set
- Start the TypeScript watcher so it auto-compiles your code whenever you save:
tsc --watch - Now, use Live Server to open your HTML file—but make sure your HTML references the compiled JS file from the
distfolder, not the original .ts file. For example:<!-- Correct --> <script src="./dist/app.js"></script> <!-- Wrong (will throw errors!) --> <script src="./src/app.ts"></script>
Option 2: Use a Modern Dev Server (Vite, for Example)
If you want a more seamless workflow (no manual compilation steps), switch to a tool like Vite that handles TS out of the box:
- Initialize a new Vite project with TypeScript support:
npm create vite@latest my-ts-project -- --template vanilla-ts - Navigate into your project folder:
cd my-ts-project - Install dependencies:
npm install - Start the dev server (it will auto-open your browser and handle live reloading + TS compilation):
Any changes you make to your TS files will instantly show up in the browser—no extra steps needed!npm run dev
Quick Troubleshooting Tips
- Double-check your HTML script tags: Never link directly to .ts files—always use the compiled .js output.
- Verify your
tsconfig.jsonsettings: If compiled JS isn't showing up in yourdistfolder, make sureoutDirandrootDirare pointing to the right folders. - Ensure your TS code has no syntax errors: The
tsc --watchcommand will log compilation errors in your terminal—fix those first before checking the browser.
内容的提问来源于stack exchange,提问作者Steven Colocho

