Skip to content

Instantly share code, notes, and snippets.

@haggen
Last active May 6, 2023 17:34
Show Gist options
  • Save haggen/941b62a2418b1a92977c71a10389c1b1 to your computer and use it in GitHub Desktop.
Save haggen/941b62a2418b1a92977c71a10389c1b1 to your computer and use it in GitHub Desktop.
Script to automate creating new components in a React application.
#!/usr/bin/env bash
#
# Create React Component.
#
# Sane defaults.
# -e Exit on error.
# -u Whine on undefined variables.
# -o pipefail Exit main script if pipe process fails.
set -euo pipefail
# Version.
version="1.0.0"
# Print manual.
help() {
cat <<-EOF >&2
About:
Create React Component v$version by Arthur <[email protected]>
Usage:
$0 [options] <components>
Arguments:
<components> Space separated component names, e.g. Form Input Button.
Options:
--help -h Print manual.
--directory -d Directory where components are located. Will auto detect. Defaults to current directory.
--typescript -t Use TypeScript.
--stylesheet -s Create stylesheet.
EOF
}
# Check for required arguments.
if ! test $# -ge 1; then
help
exit
fi
# Parse arguments.
args=$(getopt -n "$0" -o hd:ts -l help,directory:,typescript,stylesheet -- "$@")
# Bail if parsing failed.
if test $? -ne 0; then
exit 1
fi
# Put arguments back into $@.
eval set -- "$args"
# Handle arguments.
while :; do
case "$1" in
-h|--help)
help
exit
;;
-d|--directory)
prefix="$2"
shift 2
;;
-t|--typescript)
typescript=1
shift
;;
-s|--stylesheet)
stylesheet=1
shift
;;
--)
shift
break
;;
esac
done
# Solve directory.
if test -d "${directory=}"; then
prefix="$directory"
elif test -d "src/components"; then
prefix="src/components"
elif test -d "components"; then
prefix="components"
else
prefix="."
fi
# Batch mode.
if test $# -gt 1; then
flags=(-d "$prefix")
if test -n "${typescript=}"; then
flags+=(-t)
fi
if test -n "${stylesheet=}"; then
flags+=(-s)
fi
for component in "$@"; do
"$0" "${flags[@]}" "$component"
done
exit 0
fi
name="$1"
path="$prefix/$name"
# Prevent overwriting.
if test -d "$path"; then
printf "%s" "$0: component '$name' already exists\n" >&2
exit 1
fi
# Create component directory.
mkdir "$path"
# Set component file.
file="$path/index.jsx"
if test -n "${typescript=}"; then
file="$path/index.tsx"
fi
# Use stylesheet.
if test -n "${stylesheet=}"; then
touch "$path/style.module.css"
printf "%s\n\n" "import classes from \"./style.module.css\";" >> "$file"
fi
# Use TypeScript.
if test -n "${typescript=}"; then
printf "type Props = {};\n\n" >> "$file"
printf "%s\n" "export function $name({}: Props) {" >> "$file"
else
printf "%s\n" "export function $name() {" >> "$file"
fi
# Write the rest of the component.
cat <<-EOF >> "$file"
return (
<>$name</>
);
}
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment