npm_pack.sh

43 阅读1分钟
#!/bin/bash

# Ensure we're in the project root
cd "$(dirname "$0")"

# Function to get the current version from the main package.json
get_current_version() {
    node -p "require('./package.json').version"
}

# Function to increment version
increment_version() {
    local version=$1
    local release=${2:-patch}

    IFS='.' read -ra ver <<< "$version"
    major=${ver[0]}
    minor=${ver[1]}
    patch=${ver[2]}

    case $release in
        major)
            major=$((major + 1))
            minor=0
            patch=0
            ;;
        minor)
            minor=$((minor + 1))
            patch=0
            ;;
        patch)
            patch=$((patch + 1))
            ;;
    esac

    echo "${major}.${minor}.${patch}"
}

# Get the current version
current_version=$(get_current_version)

# Allow user to choose version increment
echo "Current version: $current_version"
echo "Choose version increment:"
echo "1) Patch (default)"
echo "2) Minor"
echo "3) Major"
echo "4) Use current version"
echo "5) Enter custom version"
read -p "Enter your choice (1-5): " choice

case $choice in
    2)
        new_version=$(increment_version "$current_version" minor)
        ;;
    3)
        new_version=$(increment_version "$current_version" major)
        ;;
    4)
        new_version=$current_version
        ;;
    5)
        read -p "Enter custom version: " new_version
        ;;
    *)
        new_version=$(increment_version "$current_version")
        ;;
esac

echo "Using version: $new_version"

# Build the project
npm run build

# Create a temporary package.json in the dist directory
echo "{\"name\": \"my-app-dist\", \"version\": \"$new_version\"}" > dist/package.json

# Pack the dist directory
npm pack ./dist

# Remove the temporary package.json
rm dist/package.json

echo "Dist directory packed successfully with version $new_version!"

# Optionally update the main package.json with the new version
read -p "Do you want to update the main package.json with this new version? (y/n) " update_main
if [[ $update_main == "y" ]]; then
    npm version $new_version --no-git-tag-version
    echo "Main package.json updated to version $new_version"
fi