I am trying to figure out how can I debug a script, in VS Code, that executes in the browser, but its source is Typescript.
I provide my full setup so far here - package.json
:
"scripts": {
"app:debug": "tsup --watch --config tsup.debug.config.ts"
},
"devDependencies": {
"tsup": "^8.5.0",
"typescript": "^5.8.3"
}
app.ts
:
const message: string = "Hello, TypeScript!";
console.log(message);
tsup.debug.config.ts
:
import { defineConfig } from 'tsup';
export default defineConfig({
format: ['iife'],
dts: false,
sourcemap: true,
minify: false,
bundle: true,
clean: false,
entry: { ['app']: 'src/app.ts' },
outDir: 'public'
});
Running it:
npm run app:debug
Serving .js
file:
npx serve -p3001 public/
/mysite/index.html
page that uses the script:
<!DOCTYPE html>
<html>
<head>
<!--app.ts.global.js is the default output file. app.ts.global.js.map is the default output map file.-->
<script src='http://localhost:3001/app.ts.global.js'></script>
</head>
<body>
</body>
</html>
Serving the page:
npx serve -p 3000 /mysite/
I want to be able to add a breakpoint to app.ts
and when I access http://localhost:3000, VS Code to break at that breakpoint.
Is this possible?
Yes, it's possible to debug typescript
files in VS Code while the javascript
generated by tsup
is running in the browser.
I reproduced your setup with a few minor tweaks listed below:
package.json
: add {} around your content to make it a valid JSON.
Run npm install
Generate .js
and .map
files with the same command and config file as your setup:
npm run app:debug
/mysite/index.html
: remove .ts
from the file name to match tsup
output. Change
<script src='http://localhost:3001/app.ts.global.js'>
to
<script src='http://localhost:3001/app.global.js'>
Serving .js
file: Add space between -p and port number in command
npx serve -p 3001 public/
Serving the .html
page: remove the first slash from /mysite/
to mysite/
.
npx serve -p 3000 mysite/
Add .vscode/launch.json
file to your folder. This file contains configuration for VS Code debugging. Copy this into this file:
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Chrome",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/public"
}
]
}
Note, webRoot
value is "${workspaceFolder}/public", not the default "${workspaceFolder}" - this is important to make breakpoints work.
Save the launch.json
file, click on Run and Debug
in VS Code left side menu. You should have Chrome
option next to the start debugging button.
Set a breakpoint in the app.ts
in VS Code then click on Run and Debug
and click Start Debugging (F5)
in VS Code. It should load your index.html
page in the browser and stop on a breakpoint in VS Code: