Last active
November 9, 2023 19:34
-
-
Save orvn/5ff8b5bda0231dc1091d056cd3714286 to your computer and use it in GitHub Desktop.
A shell script that forces symlinks to be created within a workspace (package) of an npm monorepo, so that `node_modules` in the repo root are referenced symbolically in the workspace's `node_modules`. This script can be run by the CI or a build script to forcefully ensure workspaces know about dependencies available in the repo root. It's a bi…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# A script that forces a target npm workspace to symbolically link to any root node_modules that it does not explicitly contain | |
# Example usage: ./scripts/npm-symlink.sh packages/website | |
set -o errexit | |
set -o nounset | |
set -o pipefail | |
WORKSPACE="$1" | |
echo -e "\n 🛠️ Creating forceful NPM symlinks \n" | |
# Find repo root | |
PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) | |
WORKSPACE_DIR="${PROJECT_ROOT}/${WORKSPACE}" | |
WORKSPACE_NODE_MODULES="${WORKSPACE_DIR}/node_modules" | |
ROOT_NODE_MODULES="${PROJECT_ROOT}/node_modules" | |
mkdir -p "${WORKSPACE_NODE_MODULES}" | |
create_symlinks() { | |
local package=$1 | |
local target_path=$2 | |
local root_path=$3 | |
# Scoped packages (@...) need their parent directory created | |
local parent_dir | |
parent_dir=$(dirname "${target_path}") | |
mkdir -p "${parent_dir}" | |
if [ ! -e "${target_path}" ]; then | |
ln -s "${root_path}" "${target_path}" | |
echo -e "✨ Created symlink for ${package} \n" | |
else | |
echo -e "⏩ Skipped ${package}, already exists." | |
fi | |
} | |
# Loop through root node_modules | |
for module in ${ROOT_NODE_MODULES}/*; do | |
module_name=$(basename "${module}") | |
if [[ "${module_name}" == @* ]]; then | |
# For scoped packages (@...) | |
for sub_module in "${module}"/*; do | |
sub_module_name=$(basename "${sub_module}") | |
create_symlinks "${module_name}/${sub_module_name}" "${WORKSPACE_NODE_MODULES}/${module_name}/${sub_module_name}" "${sub_module}" | |
done | |
else | |
# For non-scoped packages (most non-org packages) | |
create_symlinks "${module_name}" "${WORKSPACE_NODE_MODULES}/${module_name}" "${module}" | |
fi | |
done | |
echo -e "\n 😅 All symlinks created \n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment