Skip to content

Instantly share code, notes, and snippets.

@juandm
Last active February 27, 2023 22:16
Show Gist options
  • Save juandm/03c63bd0171ab784bc614160899d38a6 to your computer and use it in GitHub Desktop.
Save juandm/03c63bd0171ab784bc614160899d38a6 to your computer and use it in GitHub Desktop.
A guide to find and remove dead code in JavaScript and TypeScript projects

Finding, removing, and monitoring dead code

This guide considers only Javacript/Typescript projects, since the main library used on it detects dead code in this language.

How this works?

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.

Detecting 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.

Running the script

yarn find-dead-code

This will show a list of files and line numbers in which the lib has found some ☠️ dead code ☠️

CI/CD monitoring

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 ----"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment