Vite+React开发Chrome扩展:TypeScript内容脚本调试求助
调试Vite搭建的Chrome扩展中TypeScript内容脚本的问题
刚接触React,用Vite搭建了Chrome扩展项目,调试TypeScript编写的content script时遇到问题:
- 使用.js格式的内容脚本可正常调试
- 使用.ts格式时,触发断点或
debugger语句后,VS Code会打开临时的content.js文件,无法直接调试原.ts文件 - 非内容脚本的.ts文件调试正常
以下是当前的配置文件:
launch.json 配置
{ "type": "chrome", "request": "launch", "name": "Launch Extension", "url": "https://www.onet.pl/", "runtimeArgs": [ "--load-extension=${workspaceFolder}/build/", "--remote-debugging-port=9222" ], "sourceMaps": true, "webRoot": "${workspaceFolder}/src" }
vite.config.ts 配置
export default defineConfig({ plugins: [ react(), viteStaticCopy({ targets: [ { src: "public/manifest.json", dest: ".", }, ], }), ], build: { outDir: "build", sourcemap: true, // 确保sourcemap已开启 rollupOptions: { input: { main: "./index.html", // 主应用 content: "./src/content.ts", // 内容脚本 }, output: { entryFileNames: "assets/[name].js", // 输出文件名 manualChunks: undefined, // 禁用代码分割 }, }, target: "esnext", minify: false, }, });
解决方法
1. 确保manifest.json的内容脚本配置正确
检查public/manifest.json中的content script配置,指向编译后的JS文件,若使用ES模块需指定"type": "module":
{ "content_scripts": [ { "matches": ["https://www.onet.pl/*"], "js": ["assets/content.js"], "type": "module" // 若内容脚本是ES模块则添加 } ] }
2. 调整Vite的Sourcemap配置
将Vite的sourcemap设置为'inline',确保sourcemap数据嵌入到编译后的JS文件中,避免路径解析问题:
修改vite.config.ts的build部分:
build: { // ...其他配置 sourcemap: 'inline', // 替换原来的true }
3. 优化launch.json的路径映射
在launch.json中添加sourceMapPathOverrides,明确映射编译后的JS文件到原TS文件的路径:
{ "type": "chrome", "request": "launch", "name": "Launch Extension", "url": "https://www.onet.pl/", "runtimeArgs": [ "--load-extension=${workspaceFolder}/build/", "--remote-debugging-port=9222" ], "sourceMaps": true, "webRoot": "${workspaceFolder}/src", "sourceMapPathOverrides": { "webpack:///*": "${webRoot}/*", "http://*/*": "${webRoot}/*", "https://*/*": "${webRoot}/*", "/*": "${webRoot}/*", "assets/content.js": "${webRoot}/content.ts" // 直接映射内容脚本 } }
4. 禁用VS Code的临时文件自动加载
在VS Code设置中搜索debug.javascript.usePreview,将其设置为false,避免调试时自动打开编译后的临时JS文件。
完成以上配置后,重新执行npm run build构建项目,再启动调试,即可直接在原content.ts文件中触发断点调试。
内容的提问来源于stack exchange,提问作者Marcin J
相关产品推荐
相关产品推荐

