Bash script to run CDK synth only if there are changed TS files

The cdk synth command can be pretty slow, even when running for a single small stack. We also often want to run the CDK synth command regularly as part of local development setups, so it’s nice to skip the re-synth if no relevant files have changed.

Here’s a bash script that checks for changed TypeScript source files by comparing their timestamp to that of the generated template file from the previous synth. This way we only run CDK synth when we find a relevant change.

If a previously generated template file is not found, then the script assumes a re-synth is necessary. The check can also be overridden by setting the FORCE_REBUILD environment variable to 1.

#!/usr/bin/env bash

set -euo pipefail

IFS=$'\n\t'
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
TEMPLATE_FILE="${SCRIPT_DIR}/../cdk.out/foobar-stack.template.json"

TEMPLATE_MISSING=false
if [[ ! -f "${TEMPLATE_FILE}" ]]; then
  TEMPLATE_MISSING=true
fi

TS_FILES_CHANGED=false
if [[ -f "${TEMPLATE_FILE}" ]]; then
  set +e
  if find "${SCRIPT_DIR}/../src" -type f -newer "${TEMPLATE_FILE}" \
    -name '*.ts' 2>/dev/null | grep -q .; then
    TS_FILES_CHANGED=true
  fi
  set -e
fi

(
  if [[ "${FORCE_REBUILD:='0'}" == '1' \
     || "${TEMPLATE_MISSING}" == true \
     || "${TS_FILES_CHANGED}" == true ]]; then
    cd "${SCRIPT_DIR}/.."
    echo '... Rebuilding CDK app for local dev ...'
    cdk synth 'foobar-stack' --no-staging --context 'stage=local'
  else
    echo 'Source files have not changed, skipping CDK synth'
  fi
  echo '✔ Local dev CDK app build is up to date'
)

The check for changed files is handled by the find command inside the if condition for setting TS_FILES_CHANGED:

find "${SCRIPT_DIR}/../src" -type f -newer "${TEMPLATE_FILE}" -name '*.ts'

It looks in the src directory for files with a filename ending in .ts that are newer than the template file specified by the TEMPLATE_FILE variable at the top of the script. Adjusting this find command would allow you to check for various other changed files that are relevant in your project.


By the way, you can hire me as a freelance AWS developer to get your project done on time and in budget.


Tech mentioned