简体   繁体   中英

Add ts-prune to lint-staged

I'd like to run ts-prune in order to detect dead code on the files staged for commit using lint-staged .

I've tried the following:

"find-deadcode": "ts-prune -e",
...
"lint-staged": {
  "*.{js,ts,tsx}": [
    "npm run find-deadcode",
    "eslint --fix"
  ]
}

However it lists all files with dead code instead of only the ones that are going to be commmited.

Is there a way to achieve this?

lint-staged works by passing the list of staged files to the specified commands. Since ts-prune doesn't take a list of files as an argument it doesn't work out-of-the-box with lint-staged .

An alternative to @James's answer if you want to use lint-staged is to wrap ts-prune in a script that takes the file list supplied by lint-staged and filters the output using it.

tools/ts-prune-included.sh

const {exec} = require('child_process');

const includedFiles = process.argv
  .slice(2)
  .map(path => path.replace(process.cwd() + '/', ''));

exec('npx ts-prune', (_, stdout) => {
  const result = stdout
    .split('\n')
    .filter(line => includedFiles.some(file => line.startsWith(file)))
    .join('\n');

    console.log(result);
    process.exit(result ? 1 : 0)
})

And you'd use it in the lint-staged config like so:

"lint-staged": {
  "*.{js,ts,tsx}": [
    "node tools/ts-prune-included.js",
    "eslint --fix"
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM