tsc生成sourceMapURL路径错误问题求助
解决TypeScript SourceMap路径错误(Electron Windows应用场景)
问题描述
配置"sourceMaps": true后,TypeScript将src/services/database.ts编译为dist/services/database.js和dist/services/database.js.map,但生成的js文件末尾sourceMappingURL仅为database.js.map,导致Electron DevTools错误地到dist/根目录加载map文件,而非map实际所在的子目录,触发如下加载错误:
DevTools failed to load source map: Could not load content for file:///C:/Users/me/project/dist/floatingnotification.js.map: Unexpected end of JSON input
解决方案
方案1:修复TS编译的路径结构(推荐)
问题根源是TypeScript未明确输入文件的根目录,导致编译后路径解析异常。在tsconfig.json的compilerOptions中添加rootDir配置,强制TS保持与src目录一致的输出结构:
修改后的compilerOptions片段:
"compilerOptions": { // 原有配置... "rootDir": "./src", // 新增:指定输入文件的根目录 "sourceMap": true, "outDir": "dist" }
添加后重新执行编译,TS会严格按照src下的目录结构生成dist文件,且js文件中的sourceMappingURL会指向同一子目录下的map文件,DevTools即可正确加载。
方案2:统一将map文件移至dist根目录
若方案1无法解决,可通过脚本将所有map文件集中到dist根目录,并修正js文件中的sourceMappingURL:
- 在项目根目录创建
post-build.js脚本:
const fs = require('fs').promises; const path = require('path'); async function adjustSourceMaps() { const distRoot = path.resolve(__dirname, 'dist'); async function processDir(currentDir) { const entries = await fs.readdir(currentDir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(currentDir, entry.name); if (entry.isDirectory()) { await processDir(fullPath); } else if (entry.name.endsWith('.js')) { // 读取并修改js文件的sourceMappingURL let content = await fs.readFile(fullPath, 'utf8'); const mapMatch = content.match(/\/\/# sourceMappingURL=([^\\/]+)\.map/); if (mapMatch) { const mapFileName = `${mapMatch[1]}.map`; const oldMapPath = path.join(currentDir, mapFileName); const newMapPath = path.join(distRoot, mapFileName); // 移动map文件到根目录(忽略重复文件) try { await fs.rename(oldMapPath, newMapPath); } catch (err) { if (err.code !== 'EEXIST') throw err; } // 计算相对路径并替换 const relativePath = path.relative(currentDir, distRoot).replace(/\\/g, '/'); const newUrl = relativePath ? `${relativePath}/${mapFileName}` : mapFileName; content = content.replace(mapMatch[0], `//# sourceMappingURL=${newUrl}`); await fs.writeFile(fullPath, content, 'utf8'); } } } } await processDir(distRoot); } adjustSourceMaps().catch(console.error);
- 在
package.json的scripts中添加编译后钩子:
"scripts": { "build": "tsc", "postbuild": "node post-build.js" }
执行npm run build后,脚本会自动移动所有map文件到dist根目录,并修正js文件中的路径引用。
内容的提问来源于stack exchange,提问作者andypaxo
相关产品推荐
相关产品推荐

