Skip to content

Instantly share code, notes, and snippets.

@mkhizeryounas
Created May 5, 2023 00:04
Show Gist options
  • Save mkhizeryounas/d9a57252dd772a0febd9ba25d208efa4 to your computer and use it in GitHub Desktop.
Save mkhizeryounas/d9a57252dd772a0febd9ba25d208efa4 to your computer and use it in GitHub Desktop.
Patch npm packages script using patch-package
#!/usr/bin/env sh
ROOT_DIR=$(cd "$(dirname "$0")/..";pwd -P)
PACKAGE_NAME=${1:-}
COMPLETE_FLAG="--complete"
if [ -z "$PACKAGE_NAME" ]; then
echo "Usage ./`basename $0` <app-name> <package>"
echo " i.e. ./`basename $0` applicant-app react-native"
exit 1
fi
APP_DIR=$ROOT_DIR
MAIN_PACKAGE_JSON=$APP_DIR/package.json
PACKAGE_VERSION=$(node -e "console.log(require('$MAIN_PACKAGE_JSON').dependencies['$PACKAGE_NAME'] || require('$MAIN_PACKAGE_JSON').devDependencies['$PACKAGE_NAME'])")
if [ $PACKAGE_VERSION == "undefined" ]; then
echo ""
echo "Package '$PACKAGE_NAME' does not appear to exist in $MAIN_PACKAGE_JSON"
echo ""
exit
fi
PACKAGE=$PACKAGE_NAME@$PACKAGE_VERSION
TEMP_DIR=$TMPDIR/patch-package-$PACKAGE_NAME
PATCHES_DIR=$APP_DIR/patches
COMPLETE=${2:-}
if [ $COMPLETE == $COMPLETE_FLAG ]; then
echo ""
echo "Creating patch for $PACKAGE..."
echo ""
mkdir -p $TEMP_DIR
cd $TEMP_DIR
ls -al
npx patch-package $PACKAGE_NAME
PATCH=$(ls patches/)
cp patches/$PATCH $PATCHES_DIR
cd $APP_DIR
rm -rf $TEMP_DIR
echo ""
echo "Copied $PATCH to $PATCHES_DIR"
echo ""
exit
fi
echo ""
echo "Preparing patch for $PACKAGE..."
echo ""
mkdir -p $TEMP_DIR
cd $TEMP_DIR
yarn init -y
yarn add $PACKAGE
echo ""
echo "Now open $TEMP_DIR/node_modules/$PACKAGE_NAME and make the change you need. When complete, run:"
echo ""
echo "cd $ROOT_DIR && sh $0 $1 $2 $COMPLETE_FLAG"
echo ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment