React Native and Gradle

Short and to the point, for my future reference and anyone else that might be banging their head against their keyboard dealing with Gradle during React Native development.

Recently as I was updating React Native to the latest version (using this invaluable tool), I faced an issue causing Gradle to constantly complain about the same issue over and over regardless of the changes to Android dependencies.

Running ./gradlew clean in /android folder didn’t help. Nuking the entire Gradle cache with rm -rf ~/.gradle/caches didn’t help. Regardless of what I did, Gradle would spit out the same error. What’s even more frustrating is sometimes the build would work fine, running through the same steps again. Cleaning the Gradle cache and nuking the cache directory would sometimes produce new results, false positives. You’d think you’re done, send the ticket to QA only to have it rejected due to build errors.

After reading this comment on Stack Overflow, I discovered that you actually need to stop the currently running Gradle daemons before nuking the cache. This is likely related to cache and build artifacts being help in memory by Gradle to speed up builds. Doing this fixed my issues with Gradle cache cleaning and nuking. The new steps should be:

# Install new React Native dependencies
yarn install
# or 
npm install

# Clean gradle cache
cd android/
./gradlew clean


Those steps should generally be enough for most use cases, however if you’re doing something that requires repeated Gradle installations and dependency management, such as updating React Native, you’re very likely to run into an issue that will require a bit more:

# Stop the Gradle daemon
cd android/
./gradlew --stop

# Nuke Gradle caches
rm -rf ~/.gradle/caches


Generally that will be enough, if this doesn’t help, you’re on your own.

I’ve done this quite often lately as I’m updating some of my older React Native projects to the latest React Native version, I’ve added this helpful function to my ~/.zshrc file to speed up this task:

function gradle_full_clean {
  if ! [ -z "$1" ]
  then
    echo "Changing to specified
      project folder $1"
    cd ~/Documents/Projects/$1
  fi

  echo "Changing to android folder"
  cd ./android

  echo "Cleaning android cache"
  ./gradlew clean

  echo "Stopping gradle daemon"
  ./gradlew --stop

  echo "Navigating back to
      root project folder"
  if ! [ -z "$1" ]
  then
    cd ~/Documents/Projects/$1
  else
    cd ..
  fi

  echo "Deleting gradle caches"
  chmod u+x ~/.gradle/caches
  rm -rf ~/.gradle/caches

  echo "Deleting node_modules"
  rm -rf ./node_modules

  echo "Installing yarn packages"
  yarn # or npm install
}