Skip to content

Instantly share code, notes, and snippets.

@selftaught
Last active August 25, 2023 01:31
Show Gist options
  • Save selftaught/51b7ab861e8e27c9e1f0422375aed558 to your computer and use it in GitHub Desktop.
Save selftaught/51b7ab861e8e27c9e1f0422375aed558 to your computer and use it in GitHub Desktop.
MUI barrel imports to direct imports
#!/usr/bin/env bash
function _sed() {
if [ `uname` = 'Darwin' ]; then
# for MacOS
sed -i '' -e "$1" "$2"
else
# for Linux and Windows
sed -i'' -e "$1" "$2"
fi
}
# only supports @package/subpackage format and nothing else atm.
function unbarrel_imports() {
COMPONENT=$1
if [[ -z $COMPONENT ]]; then
echo "missing required component param"
exit 1
fi
PKG=$(echo $COMPONENT | grep -Eo '@[^/]+' | tr -d '@')
SUBPKG=$(echo $COMPONENT | grep -Eo '\/.*$' | tr -d '/')
find "./src" -type f \( -name "*.js" -o -name "*.jsx" -o -name "*.ts" -o -name "*.tsx" \) -print0 |
while IFS= read -r -d '' file; do
IMPORTS=$(cat $file | grep -E "import\s*{.*}\s*from\s*'$COMPONENT';$" | sed 's/'$PKG'/'$PKG'\\/g')
if [[ ! -z $IMPORTS ]]; then
DIRECT_IMPORTS=$(echo $IMPORTS | grep -Eo '{.*}' | tr -d '{} ' | tr ',' "\n" | xargs -I{} echo "import {} from '@"$PKG"\/"$SUBPKG"\/{}';")
DIRECT_IMPORTS=$(echo "${DIRECT_IMPORTS//$'\n'/\\n}")
echo -n "Unbarrelling imports in $file"
_sed "s/$IMPORTS/$DIRECT_IMPORTS/g" $file
fi
done
}
if [[ ! -z $1 ]]; then
unbarrel_imports $1
else
unbarrel_imports '@mui/material'
unbarrel_imports '@mui/icon-material'
fi
# Updates barrel imports like:
#
# import { CircularProgress, Stack, Typography } from '@mui/material';
#
# To individual direct imports:
#
# import CircularProgress from '@mui/material/CircularProgress';
# import Stack from '@mui/material/Stack';
# import Typography from '@mui/material/Typography';
#
# We have this committed to a bin directory in a FE repo.
# The script is called from a husky pre-commit hook
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment