Decluttering Client Repos

Table of Contents

Knip

Knip is useful towards identifying unlisted dependencies, duplicated exports, and potential unused files, dependencies or exports.

Watch out for false positives!

Avoid blindly implementing everything reported. Look, verify, and test. Do your own searches and thinking for things like reported unused exports.

Knip is not meant for resource-core, webfonts-core, pankosmia-web, or desktop-app-*.

It is for projects constructed with a packages.json and an index.js, which it uses to step through and evaluate all includes in the app.

Setup

npm install -g knip (to install or update)

Analyzing a repo

In the root of the client repo in a terminal, enter knip. It will provide a list of any of any unused, unlisted, or duplicated things that it suspects it has found.

Example of false positives on unused exports

It will report Selection.styles.jsx as an unused export (because of the filename) even when it is in use. Be careful to not remove this file where its export is actually in use.

Example of reported duplicated exports not actually causing a problem

Selection.styles.jsx is exporting sx, which works fine as used.

Example of false positive on unused dependencies

Knip is quite good at following the include chain throughout a project. However, sometimes dependencies are in place outside of this chain, which it will miss. For example, if a package.json includes use of react-scripts in its scripts section, it’s dependency chain includes babel which includes a devDependency of @babel/plugin-proposal-private-property-in-object. Knip will miss that case and report that as an unused dependency, but in that case it is actually used.

Applying package changes while keeping local installs clean and consistent

  • Use npm ci. This removes node_modules and matches the lock file.
  • To bump a package version follow npm ci with npm install <package_name>@0.1.29 --save-exact
  • To remove a package follow npm ci with npm uninstall <package_name>
  • To add a package follow npm ci with npm install <package_name> --save-dev or npm install <package_name> -D (for devDependencies) or npm install <package-name> --save-optional

Why avoid manually editing package.json (except where not possible)?

npm i tends towards package-lock.json OS differences, and does not keep node_modules clean. Note also that following a manual package.json edit with npm prune does not update package-lock.json to reflect the removal, and does not uninstall lifecycle scripts (which let packages perform custom actions automatically).