Caching & change detection Turborepo and Github Actions
“Remote Caching”
I recently worked on a project with Turborepo and wanted to setup caching without using Vercel’s proprietary Remote Caching.
I also wanted change detection to only deploy things that have changed. Here’s how I did it.
First, let’s just setup a basic CI workflow that runs our test suite.
This file will run our tests, but does not setup any turborepo caching.
Here’s how we add the turborepo cache:
Make sure you add the --cache-dir argument to your test call. This will tell turborepo where to save and restore your cache files.
Change Detection
Alright, we have that setup, but how do we do change detection for deployments? There are honestly several ways to do this but the most generic and simplest
way is to use turborepo to detect if a package has changed and deploy it.
Let’s start with defining our own custom Github Action that we can use within our repo for change detection.
You do have to put it within a folder and the file must be called _action.yml`
This code gets pretty complex in the last bash script. Basically what we are doing is npx turbo build and having it run a “dry run” of the build. It won’t actually build the packages, it is just going to tell you what it will do.
We set the output to json using the --dry-run=json argument. This allows us to detect which packages would be built and we can assume have changed.
We use the "echo changed=<value>"" >> $GITHUB_OUTPUT syntax to set the output for the action. The output can be used in our deployment workflow to decide if we should deploy it. Let’s dive into that code.
There is a lot here to unpack, but this workflow will only deploy if our code has actually changed. It also allows us to use Github’s workflow dispatch feature to force deployments if we need to redeploy for some reason.
Let me know what you think or if you have any suggestions to make this better!