如何编写脚本自动定位并进入指定唯一目录./package
自动定位package目录并执行发布脚本的实现
核心思路
通过脚本自动遍历目录,先从当前位置向上查找包含package目录的项目根,若未找到则从当前目录的父目录向下搜索,定位到目标目录后再执行发布相关命令,无需手动切换路径。
Bash 环境实现(VSCode Bash 优先)
- 在项目根目录创建
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
- 给脚本添加执行权限:
chmod +x build.sh
- 修改
package.json的scripts:
{ "scripts": { "build": "./build.sh" } }
PowerShell 环境兼容实现
- 在项目根目录创建
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
- 修改
package.json的scripts(若使用PowerShell环境):
{ "scripts": { "build": "pwsh ./build.ps1" } }
使用说明
- 无论当前处于项目内的子目录、项目根目录还是项目外的父目录,直接运行
npm run build即可自动定位到package目录并执行后续发布命令。 - 脚本会优先向上查找项目根下的
package目录,若未找到则从当前目录的父目录向下搜索一级,完全匹配你描述的场景需求。
内容的提问来源于stack exchange,提问作者user19485937
相关产品推荐
相关产品推荐

