This guide considers only Javacript/Typescript projects, since the main library used on it detects dead code in this language.
There is a lib that provide this functionality and some recommended configs for it. The lib searches for code that is exported and not imported in other files and list them. It is also easy to ignore some directories and/or files that are ok to contain dead code.
- Add the package
yarn add -D ts-prune
- Add the script to
package.json
"scripts": {
"find-dead-code": "ts-prune -s '.*.test.ts?' -i '(used in module)|(generated)|(src/db/)|(tools/)|(presentation\\\\-generation\\\\-logic)'"
}
Command explanation:
s '.*.test.ts?'
-s: files to ignore import statementsThis is useful because code that is just imported in test files, shouldn’t be tested directly. Instead, it is recommended to test the module / function that uses it.i '(used in module)|(generated)|(src/db/)'
-i Results to be omittedThis is used to create a list of regex that can match folders/files that are ok to contain dead code. Useful for we have some code that is automatically generated.
yarn find-dead-code
This will show a list of files and line numbers in which the lib has found some ☠️ dead code ☠️
To fail a Github action if dead code is introduced you may add the command snippet below to your workflow file right after the lint
command.
- name: Check for dead code
run: |
yarn find-dead-code > dead_code
cat dead_code | if [[ $(wc -l) -gt 3 ]]; then echo "Dead code found: " && cat dead_code && exit 1; fi
echo "---- No dead code found ----"