eslint changed TypeScript files only
It’s best if a linter is applied from the beginning of a project, and with default linting rules, as that way the project benefits from the linting with the minimum possible effort.
However, we often join existing projects which have already been developed without the use of a linter, by which point there are possibly thousands of linter violations. In that situation, one option is to incrementally improve the linting by only applying the linter to changed files. New code from then on is compliant, and it’s less of a burden to sort out existing violations in existing files that developers touch as part of a change.
Here’s a quick bash script that runs eslint
against changed TypeScript files
only.
#!/usr/bin/env bash
mapfile -t CHANGED_TS < <(git diff origin/main --name-only | grep '\.ts')
if (( ${#CHANGED_TS[@]} )); then
eslint --no-error-on-unmatched-pattern "${CHANGED_TS[@]}"
fi
It uses git to get a list of files that differ from the main
branch . That
file list is passed through grep
to reduce it to TypeScript files only, just
to make it a little more efficient when we feed the list to eslint
afterwards,
as grep
is probably faster than eslint
matching rules.
The list of file names is passed to the mapfile
tool, which reads it into a
bash array. This gives us some small optimisations in handling a list of string
file names, such as allowing for file names with special characters, and
avoiding issues with word splitting when feeding the list to eslint
.
The bash if
statement that checks whether the file list is empty is important,
due to the possibility that there are no changed TypeScript files. If we ran
eslint
with an empty list like that, it would run against all existing files,
which is what we’re trying to avoid doing on an existing project.
The (( ${#CHANGED_TS[@]} ))
bash syntax checks if the array called
CHANGED_TS
contains at least one item.
We need to use the --no-error-on-unmatched-pattern
option for eslint
to
handle the situation where files have been deleted in this change. Git will
rightly include deleted file names in the change list, and by default eslint
will error when it tries to lint a file that does not exist.
Finally, the "${CHANGED_TS[@]}"
bash syntax safely passes the array of file
names to eslint
, correctly handling word splitting and so on.