Vite开发服务器Sourcemap在VScode调试器中失效或指向错误位置
CRA迁移Vite后WSL2+Fedora38环境下VSCode调试器修复方案
核心问题定位
WSL2跨环境路径映射不匹配、Sourcemap配置缺失/错误、调试器路径映射未对齐,是导致断点绑定失败、卡顿、源文件指向错误、堆栈行号偏移的主要原因。
配置修正步骤
1. 调整Vite配置(vite.config.js)
确保开发环境生成完整Sourcemap,对齐WSL2路径映射:
import { defineConfig, loadEnv } from 'vite'; import react from '@vitejs/plugin-react'; import { VitePWA } from 'vite-plugin-pwa'; import path from "path"; export default defineConfig(({ mode }) => { process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '')}; return { server: { port: 3000, host: "0.0.0.0", // 解决WSL2下文件系统权限限制 fs: { strict: false } }, build: { outDir: 'build', sourcemap: true }, // 强制开发环境生成Sourcemap,避免行号偏移 optimizeDeps: { sourcemap: true }, resolve: { alias: { 'src': path.resolve(__dirname, './src') }, }, plugins: [react(), VitePWA({ injectRegister: null, strategies: 'injectManifest', filename: 'service-worker.js', srcDir: 'src', devOptions: { enabled: true, type: "module", }, injectManifest: { maximumFileSizeToCacheInBytes: 20 * 1024 * 1024, } })], preview: { port: 3000 } }; });
2. 修正调试器配置(launch.json)
针对Chrome和Firefox适配WSL2路径映射:
{ "version": "0.2.0", "configurations": [ { "name": "Launch Chrome", "request": "launch", "type": "chrome", "url": "http://localhost:3000", "sourceMaps": true, "webRoot": "${workspaceFolder}", // 关键:映射浏览器路径到WSL本地项目目录 "pathMapping": { "/": "${workspaceFolder}" }, "skipFiles": ["**/node_modules/**"] }, { "name": "Firefox Debug", "type": "firefox", "request": "launch", "url": "http://localhost:3000", "webRoot": "${workspaceFolder}", "skipFiles": ["**/node_modules/**"], "pathMappings": [ { "url": "http://localhost:3000", "path": "${workspaceFolder}" } ], "sourceMaps": true } ] }
3. WSL2环境额外设置
- 确保VSCode安装Remote - WSL插件,工作区打开的是WSL文件系统内的项目(而非Windows挂载路径)
- 重启Vite开发服务器和VSCode调试器,清除缓存影响
验证方法
- 启动Vite开发服务器:
npm run dev - 启动对应浏览器的调试器,在本地源文件设置断点
- 触发代码逻辑,检查断点是否触发、源文件映射是否正确、堆栈行号是否匹配
内容的提问来源于stack exchange,提问作者jps_dot_dev
相关产品推荐
相关产品推荐

