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

如何使用带布尔参数的PowerShell脚本切换JS文件指定行注释状态

PowerShell 脚本实现JS环境配置自动切换

针对需求实现的脚本可接收布尔型isProduction入参,自动处理当前工作目录下api-requests.js文件中的接口地址行注释切换,无需手动修改代码。

完整脚本代码

param(
    [Parameter(Mandatory = $true)]
    [bool]$isProduction
)

# 拼接目标文件路径
$targetFilePath = Join-Path $PWD.Path "api-requests.js"

# 校验文件存在性
if (-not (Test-Path $targetFilePath -PathType Leaf)) {
    throw "执行错误:当前工作目录下不存在 api-requests.js 文件,请确认路径后重试"
}

# 读取文件内容
$fileContent = Get-Content $targetFilePath -Encoding UTF8

# 定义两行配置的标准格式
$prodConfig = 'const basicPath = "http://serviceate01:5566/";'
$testConfig = 'const basicPath = "http://serviceate01:3366/";'
$commentedProd = "// $prodConfig"
$commentedTest = "// $testConfig"

# 逐行处理配置
$processedContent = foreach ($line in $fileContent) {
    # 清理行首空白、注释标记后做精准匹配
    $coreContent = $line.TrimStart().TrimStart('/').TrimStart()
    switch ($coreContent) {
        $prodConfig {
            # 生产环境配置:isProduction为true时取消注释,否则加注释
            if ($isProduction) { $prodConfig } else { $commentedProd }
            continue
        }
        $testConfig {
            # 测试环境配置:isProduction为true时加注释,否则取消注释
            if ($isProduction) { $commentedTest } else { $testConfig }
            continue
        }
        default { $line }
    }
}

# 写回文件,使用UTF8编码适配前端文件
$processedContent | Set-Content $targetFilePath -Encoding UTF8

使用方法

将上述代码保存为.ps1后缀的PowerShell脚本文件(例如switch-api-env.ps1),在存放api-requests.js的目录下打开PowerShell终端,按需执行对应命令:

  • 切换到生产环境(5566端口生效):
    .\switch-api-env.ps1 -isProduction $true
    
    执行后文件中对应配置效果:
    const basicPath = "http://serviceate01:5566/";
    // const basicPath = "http://serviceate01:3366/";
    
  • 切换到测试环境(3366端口生效):
    .\switch-api-env.ps1 -isProduction $false
    
    执行后文件中对应配置效果:
    // const basicPath = "http://serviceate01:5566/";
    const basicPath = "http://serviceate01:3366/";
    

注意事项

  • 脚本仅匹配basicPath对应的两行端口配置,其余代码逻辑不会做任何修改
  • 匹配逻辑自动兼容行首空白、已有注释标记的场景,不会出现重复加//的问题
  • 首次使用建议提前备份原api-requests.js文件,避免误修改导致的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:45:31