You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置lint-staged仅对暂存文件执行ts-prune死代码检测?

解决lint-staged配合ts-prune仅检测暂存文件死代码的问题

ts-prune本身默认会扫描整个项目的导出,没法直接指定只检测特定文件,所以得通过过滤输出或者自定义脚本实现需求,下面是两种可行方案:

方案一:用Shell命令过滤输出

直接在lint-staged配置里通过shell命令组合,先拿到暂存文件列表,再过滤ts-prune的输出结果:

修改你的package.json里的lint-staged配置:

{
  "lint-staged": {
    "*.{js,ts,tsx}": [
      "bash -c 'ts-prune -e | grep -F \"$(git diff --cached --name-only | tr \"\\n\" \"|\")\"'"
    ]
  }
}

逻辑说明:

  1. git diff --cached --name-only:获取当前暂存区的文件列表
  2. tr "\n" "|":把换行符换成竖线,生成grep的多文件匹配模式
  3. ts-prune -e | grep -F ...:执行ts-prune并过滤输出,只保留暂存文件相关的死代码条目

注意:这个方案依赖bash环境(比如Mac/Linux的终端、Windows的Git Bash/WSL),如果是纯Windows CMD环境可能需要替换grep为findstr并调整命令格式。

方案二:用Node.js脚本处理(跨平台更可靠)

写一个自定义Node脚本,先获取暂存文件,再过滤ts-prune的输出,逻辑更灵活:

  1. 在项目根目录新建check-deadcode-staged.js:
const { execSync } = require('child_process');

// 获取暂存区的js/ts/tsx文件
const getStagedFiles = () => {
  try {
    const output = execSync('git diff --cached --name-only -- "*.{js,ts,tsx}"', { encoding: 'utf8' });
    return output.trim().split('\n').filter(file => file.length > 0);
  } catch (err) {
    return [];
  }
};

const stagedFiles = getStagedFiles();
if (stagedFiles.length === 0) process.exit(0);

// 执行ts-prune并获取输出
const tsPruneOutput = execSync('ts-prune -e', { encoding: 'utf8' }).split('\n');

// 过滤出暂存文件中的死代码条目
const deadCodeEntries = tsPruneOutput.filter(line => {
  if (!line) return false;
  // 提取ts-prune输出中的文件路径(格式:path/file.ts:行号 - 导出内容)
  const filePath = line.split(':')[0];
  return stagedFiles.includes(filePath);
});

if (deadCodeEntries.length > 0) {
  console.error('暂存文件中发现死代码:');
  console.error(deadCodeEntries.join('\n'));
  process.exit(1); // 返回非0退出码,阻止提交
} else {
  console.log('暂存文件无死代码问题');
}
  1. 修改package.json的lint-staged配置:
{
  "lint-staged": {
    "*.{js,ts,tsx}": ["node check-deadcode-staged.js"]
  }
}

这个方案跨平台兼容性更好,能处理文件名包含特殊字符的情况,也更容易根据自己的需求调整过滤逻辑。

内容的提问来源于stack exchange,提问作者rfc1484

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:15:29