Skip to content

Instantly share code, notes, and snippets.

@jleem99
Created August 5, 2024 03:12
Show Gist options
  • Save jleem99/5480038c8eb84b621a19f6244520eb10 to your computer and use it in GitHub Desktop.
Save jleem99/5480038c8eb84b621a19f6244520eb10 to your computer and use it in GitHub Desktop.
A Bash script to generate and format barrel files (index.ts) for TypeScript projects. It recursively scans directories for TypeScript files, creates export statements for default and named exports, and formats the output using Prettier if available.
#!/bin/bash
MAXDEPTH=${MAXDEPTH:-1}
BARREL_NAME=index.ts
CWD="$(pwd)"
set -e
IFS=$'\n'
function generate_barrels { (
if [ ! -d "$1" ]; then
echo -e "\033[31mError: $1 is not a directory\033[0m"
return
fi
pushd "$1" >/dev/null
### Remove Existing Barrel ###
rm -f "$BARREL_NAME"
### List Files ###
FILENAMES=($(
find . -mindepth 1 -maxdepth $MAXDEPTH ! -name '.*' ! -name 'index.*' ! -path '*/__*__*' ! -name '*.test.*' ! -name '*.mock.*' |
sed -E 's:^(.*/)([^/]*)(\.[^.]*)$:\1\2: ; s:^\./::' |
sort -u
))
echo -e "\033[36m· Generating barrel for $1 on ${#FILENAMES[@]} files...\033[0m"
# Comma separated list of files
echo -e ' → '$(
IFS=', '
echo "${FILENAMES[*]}"
) | sed -E 's:,:, :g'
# 파일이 없을 시 리턴
[ -z "$FILENAMES" ] && return
### Generate Exports ###
echo "/* Auto-generated by scripts/generate-barrels.sh */" >>"$BARREL_NAME"
echo >>"$BARREL_NAME"
for file in "${FILENAMES[@]}"; do
# Default export 존재 여부 확인
[ -n "$(cat $file.* $file/index.* 2>/dev/null | grep -E '^export (default|{ default })')" ] &&
echo "export { default as ${file##*/} } from './$file'" >>"$BARREL_NAME"
done
echo >>"$BARREL_NAME"
for file in "${FILENAMES[@]}"; do
# Named export 존재 여부 확인
[ -n "$(cat $file.* $file/index.* 2>/dev/null | grep -E '^export' | grep -vE '^export (default|{ default })')" ] &&
echo "export * from './$file'" >>"$BARREL_NAME"
done
popd >/dev/null
); }
for dir in $@; do
generate_barrels "$dir"
echo
done
if [ -x "$(command -v prettier)" ]; then
echo -e "\033[36m· Formatting barrels...\033[0m"
for dir in $@; do
[ -f "$dir/$BARREL_NAME" ] && prettier --write "$dir/$BARREL_NAME" >/dev/null &
done
fi
wait
echo
echo -e "\033[32mDone!\033[0m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment