You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写脚本自动定位并进入指定唯一目录./package

自动定位package目录并执行发布脚本的实现

核心思路

通过脚本自动遍历目录,先从当前位置向上查找包含package目录的项目根,若未找到则从当前目录的父目录向下搜索,定位到目标目录后再执行发布相关命令,无需手动切换路径。


Bash 环境实现(VSCode Bash 优先)

  1. 在项目根目录创建build.sh脚本,内容如下:
#!/bin/bash

TARGET_DIR="package"

# 向上遍历查找项目根下的package目录
current_dir=$(pwd)
while [[ "$current_dir" != "/" ]]; do
    if [[ -d "$current_dir/$TARGET_DIR" ]]; then
        cd "$current_dir/$TARGET_DIR"
        break
    fi
    current_dir=$(dirname "$current_dir")
done

# 若向上未找到,从当前目录的父目录向下搜索一级目录
if [[ ! -d "$(pwd)" || "$(basename "$(pwd)")" != "$TARGET_DIR" ]]; then
    parent_dir=$(dirname "$(pwd)")
    found_dir=$(find "$parent_dir" -type d -name "$TARGET_DIR" -maxdepth 1 | head -n 1)
    if [[ -n "$found_dir" ]]; then
        cd "$found_dir"
    else
        echo "Error: $TARGET_DIR directory not found in project"
        exit 1
    fi
fi

# 执行发布流程命令
svelte-kit sync
svelte-package
npm version patch
npm publish
  1. 给脚本添加执行权限:
chmod +x build.sh
  1. 修改package.json的scripts:
{
  "scripts": {
    "build": "./build.sh"
  }
}

PowerShell 环境兼容实现

  1. 在项目根目录创建build.ps1脚本,内容如下:
$targetDir = "package"

# 向上遍历查找包含package目录的项目根
$currentDir = Get-Location
$rootDir = (Get-Volume -DriveLetter ($currentDir.Path[0])).RootDirectory
while ($currentDir.Path -ne $rootDir) {
    $testPath = Join-Path -Path $currentDir.Path -ChildPath $targetDir
    if (Test-Path -Path $testPath -PathType Container) {
        Set-Location -Path $testPath
        break
    }
    $currentDir = $currentDir.Parent
}

# 若向上未找到,从当前目录的父目录向下搜索一级
if ((Get-Location).Name -ne $targetDir) {
    $parentDir = (Get-Location).Parent.FullName
    $foundDir = Get-ChildItem -Path $parentDir -Directory -Name $targetDir | Select-Object -First 1
    if ($foundDir) {
        Set-Location -Path (Join-Path -Path $parentDir -ChildPath $foundDir)
    } else {
        Write-Error "Error: $targetDir directory not found in project"
        exit 1
    }
}

# 执行发布流程命令
svelte-kit sync
svelte-package
npm version patch
npm publish
  1. 修改package.json的scripts(若使用PowerShell环境):
{
  "scripts": {
    "build": "pwsh ./build.ps1"
  }
}

使用说明

  • 无论当前处于项目内的子目录、项目根目录还是项目外的父目录,直接运行npm run build即可自动定位到package目录并执行后续发布命令。
  • 脚本会优先向上查找项目根下的package目录,若未找到则从当前目录的父目录向下搜索一级,完全匹配你描述的场景需求。

内容的提问来源于stack exchange,提问作者user19485937

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:21:49