Vue+Vite项目中tslog日志文件名显示错误问题求助
解决tslog日志显示tslog.js而非实际调用文件的问题
1. 调整tslog核心配置
直接用以下Logger实例配置,重点设置栈追踪相关参数:
import { Logger } from "tslog"; const logger = new Logger({ displayFilePath: "relative", // 显示项目内相对路径,也可设为"absolute" stackDepthLevel: 2, // 跳过tslog自身的调用栈层级,若封装了日志工具函数则改成3 ignoreStackLevels: 0, displayFunctionName: true, // 可选,方便查看调用日志的函数名 });
注:如果把tslog封装成了全局工具(比如在
utils/logger.ts里统一导出),调用栈会多一层,stackDepthLevel需要再加1,自己测试几次就能找到合适的数值。
2. 配置Vite保留sourcemap
Vite开发环境默认生成sourcemap,但要确保没被优化关闭,修改vite.config.ts:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], build: { sourcemap: true, // 生产环境需要日志行号的话也得开启 }, optimizeDeps: { esbuildOptions: { sourcemap: true, // 依赖预构建时生成sourcemap,确保tslog能解析正确路径 }, }, })
3. 检查TypeScript编译配置
确保tsconfig.json里开启sourcemap,否则编译后的代码没有路径映射:
{ "compilerOptions": { "sourceMap": true, "inlineSourceMap": false, "inlineSources": false } }
4. 自定义路径过滤(可选)
如果仍显示node_modules内的路径,可自定义函数过滤:
import { Logger } from "tslog"; import path from "path"; const logger = new Logger({ displayFilePath: (filePath) => { // 把绝对路径转为项目内相对路径,同时适配Windows路径格式 return path.relative(process.cwd(), filePath).replace(/\\/g, "/"); }, stackDepthLevel: 2, });
内容的提问来源于stack exchange,提问作者LittleFighter
相关产品推荐
相关产品推荐

