【问题标题】:Change line in JS file in a post-build event (Visual Studio)在构建后事件中更改 JS 文件中的行(Visual Studio)
【发布时间】:2020-06-26 12:28:13
【问题描述】:

我有一个 JS 文件,其中包含需要在部署时更新的路径字段。我没有看到构建后事件允许自己替换文本或整行,所以我创建了一个批处理文件来这样做。但是,我遇到了一些奇怪的错误。

尝试使用带有 powershell 的批处理替换字符串会引发单引号被转义的错误:

powershell -Command "(gc Utility.js) -replace 'var applicationRoot = \'\/WebApplication;\'', 'var applicationRoot = \'\';' | Out-File -encoding ASCII myFile.txt"

取出单引号,看看它是否至少会运行给出一个无法识别的错误:

powershell -Command "(gc Utility.js) -replace 'var applicationRoot = \/WebApplication;', 'var applicationRoot = ;' | Out-File -encoding ASCII myFile.txt"

我将其称为构建后事件:

call "$(SolutionDir)Scripts\ChangeJSFile.bat"

有什么想法吗?

【问题讨论】:

  • 请考虑支持或接受您认为有帮助的任何答案。

标签: visual-studio powershell post-build-event


【解决方案1】:

就我个人而言,我会做一些不同的事情。

假设您在 Utility.js 所在项目的根目录中有一个名为 _PostBuild.ps1 的 Powershell 脚本。该 .ps1 脚本包含以下内容:

param(
    [string] $pathToJsFile,
    [string] $toReplace = "var applicationRoot = '/WebApplication';",
    [string] $replaceWith = 'var applicationRoot = ;'
)

$fileContent = Get-Content -Path $pathToJsFile
$newContent = $fileContent.Replace($toReplace, $replaceWith)
Set-Content -Path $pathToJsFile -Value $newContent

然后,假设上述项目有如下构建后操作:

Powershell.exe -ExecutionPolicy Bypass -NoProfile -NonInteractive -Command "$(ProjectDir)\_PostBuild.ps1" -pathToJsFile "$(ProjectDir)\Utility.js"

这将允许您在成功构建时对 Utility.js 执行字符串替换。

显然,您可能希望根据您的项目结构对构建后操作进行一些编辑。

【讨论】:

    【解决方案2】:

    这是一场轻微的噩梦,但我想我有一个解决方案。基本上唯一的问题是你逃到哪里去了。

    powershell -Command "(gc Utility.js) -replace \"var applicationRoot = '/WebApplication;'\", \"var applicationRoot = ';'\" | Out-File -Encoding ascii myFile.txt"
    

    【讨论】:

      【解决方案3】:

      有问题的部分是将最里面的单引号逐字传递给 PowerShell。相同类型的引号内的文字引号将需要某种转义。您在这里遇到这种情况,因为您的 -replace 组件被单引号包围,但打算匹配文字单引号。在这些情况下,您可以简单地使用两个单引号,从而转义一个单引号。

      powershell -Command "(gc Utility.js) -replace 'var applicationRoot = ''/WebApplication;''', 'var applicationRoot = '''';' | Out-File -encoding ASCII myFile.txt"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        相关资源
        最近更新 更多