【问题标题】:Automatic JavaScript Compression with PowerShell使用 PowerShell 自动压缩 JavaScript
【发布时间】:2011-09-20 15:07:20
【问题描述】:

我正在寻找编写一个脚本,该脚本将获取一堆 .js 文件,对其进行压缩,然后用同一文件夹中的新文件替换旧文件。我尝试了一些事情,但我发现自己不断遇到新问题,因此我认为最好求助于对我有更好理解的人并重新开始。

谁能指出我正确的方向?

更新: 我正在使用一组与此类似的命令:

>Get-ChildItem c:\NewFolder\ -recurse |
&java -jar yuicompressor-2.4.6

它似乎并不想允许这种类型的输出使用。我确信有一种方法可以完成这项工作,但是对于 PowerShell 来说还是相当新的,我不太有信心自己能解决这个问题。

更新: 使用下面建议的命令字符串,我可以让 powershell 给我似乎是从新压缩的 .js 中读取的内容,但它不会用压缩文件替换现有文件或将其写入我相信的标准输出以 [filename].min.js 格式位于同一目录中。

更新: 建议命令的修改版本似乎可以解决问题!

>Get-ChildItem c:\NewFolder\ -exclude jquery*.js,*min.js -recurse | %{java -jar yuicompressor-2.4.6.jar ($_.fullname) -o ($_.fullname)}

但是,当命令在 PowerShell 中运行时,奇怪的是,我从 PowerShell 收到一条关于 Java 命令的错误消息...

java.exe : 在 line:4 char:72 + Get-ChildItem c:\Scripts\ -排除 jquery*.js,*min.js -recurse | %{java .fullname) -o ($.fullname)} + CategoryInfo : NotSpecified: (:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError 用法:java -jar yuicompressor-x.y.z.jar [选项] [输入文件]

全局选项 -h, --help 显示此信息 --type 指定输入文件的类型 --charset 使用读取输入文件 --line-break 在指定列号后插入换行符 -v, --verbose 显示信息性消息和警告 -o 将输出放入 .默认为标准输出。 可以使用以下语法处理多个文件: java -jar yuicompressor.jar -o '.css$:-min.css' *.css java -jar yuicompressor.jar -o '.js$:-min.js' *.js

JavaScript 选项 nomunge 仅缩小,不要 obfuscate preserve-semi 保留所有分号 disable-optimizations 禁用所有微优化

如果没有指定输入文件,则默认为标准输入。在这种情况下, “类型”选项是必需的。否则,需要“类型”选项 仅当输入文件扩展名既不是“js”也不是“css”时。

知道 PowerShell 试图告诉我什么吗?

【问题讨论】:

    标签: javascript powershell compression


    【解决方案1】:

    尝试这样做:

    Get-ChildItem c:\NewFolder\ -recurse | %{java -jar yuicompressor-x.y.z.jar $_.fullname}
    

    %{..}foreach-object 的别名。您从 c:\Newfolder (及其子目录)获取一组文件,并将其中的每一个作为对象传递给管道中的下一个组件。这部分是一个既不支持流水线也不支持对象的外部组件,您将它包装在 foreach 中,并以它可以理解的形式提供文件 - 文件的全名(包括路径)。

    【讨论】:

    • 非常感谢您的建议 - 它确实让我很接近,但我还没有完全到那里。您的命令似乎为每个文件运行压缩,但不会将其写入输出 .js 以替换先前未压缩的文件,甚至使用不同的名称,例如 [filename].min.js。我将在原始问题中添加更多信息
    • 你实际上比我想象的更接近我 - 你基本上给了我答案 manojlds 所以,非常感谢你的帮助!我认得你的名字,所以我有一种感觉,虽然我以前的任何问题都没有得到你的答案,但你过去毫无疑问地通过简单地回答了别人的问题来帮助我,所以我会还要感谢您在 stackoverflow.com 上的角色。我敢肯定,这常常是不言而喻的,但我认为社区非常感谢您的帮助。
    • @ShowStopper - 如果这解决了您的问题,您应该将其标记为答案(每个答案都有一个复选标记)。对于奖励积分,您也可以对答案进行投票。
    【解决方案2】:

    此主题可能会为您提供一些答案。 What do you use to minimize and compress JavaScript libraries?

    也就是说,我相信YUI compressor 有一个可以从 PowerShell 启动的独立可执行文件。

    【讨论】:

    • 好吧,这绝对是一个开始,在玩过 YUI 和 Google 的 Closure Compiler 之后,我觉得我已经接近使用 PowerShell 完成这一切,但我在一个关键元素上遇到了问题。
    【解决方案3】:

    所以,我想我终于可以回馈这个社区了。我应该首先说我以前从未使用过 Powershell 并且真的不喜欢它。我很高兴 bash 现在随 Windows 一起提供。但是,我为一位朋友准备了一个有趣的项目,该项目在 win 服务器上运行,并且需要在将他的 .net 应用程序代码部署到他的 ec2 实例后编写一些东西来运行。我知道大约有十几种更好的方法可以使用真正的构建工具来做到这一点,但是……有时你想要一个脚本。希望你们觉得它有用。它要求您安装 java 并拥有闭包 jar;您可以尝试使用其他缩小工具。

    我需要在这篇文章中感谢 Chase Florell 让我朝着正确的方向开始:How to version javascript and css files as part of a powershell build process?

    ##################################################################
    # minimizeJS.ps1                                                 #
    # This file removes all non-minified javascript resources        #
    # and then updates all html and aspx pages to point to the       #
    # minified js if they are not already.                           #
    #                                                                #
    # Version 1.0                                                    #
    # Usage: minimizeJS.ps1 -debug true|false                        #
    ##################################################################
    param($debug=$true)  #you can remove the =$true to force a user to specify
    $maxFiles = Get-ChildItem -Path ./* -Include *.js -Exclude *.min.js, *.min.comp.js -Recurse 
    $filesContainingResourceRefs = Get-ChildItem -Path ./* -Include *.html, *.aspx -Recurse 
    $fileCollection = New-Object System.Collections.ArrayList
    
    $closureJAR = 'C:\closure\compiler.jar'
    $javaLocation = 'C:\Program Files\Java\jre1.8.0_131\bin\java.exe'
    
    #Make sure debug flag is set one way or the other
    if (!$debug){
      Write-Host "Debug has not been set.  Please use the -debug true|false argument."
      Exit
    }elseif ($debug -eq $true){
      Write-host "Running with debug mode set to $debug."
    }elseif ($debug -eq $false){
      Write-host "Running wiht debug mode set to $debug."
    }else{
      Write-host "Debug has not been set properly.  Please use the -debug true|false argument."
      Exit
    }
    
    #First find everything we have a minified js version of, create an object of their names and paths, and delete the non-min file
    Write-Host "Beginning minification of JS files.  Debug is $debug"
    foreach ($file in $maxFiles)
        {
            $fileOld = $file.FullName
            $fileNew = $file.FullName.Replace(".js", ".min.js")
            if ($debug -eq $true){
              #Write-Host java -jar $closureJAR --js $fileOld --js_output_file $fileNew
              Write-Host "  ArgList is:  -jar  $closureJAR --js $fileOld --js_output_file $fileNew"
            }else{
                Write-Host "  Minifying: $fileOld"
                Start-Process -FilePath $javaLocation `
                 -ArgumentList "-jar $closureJAR --js $fileOld --js_output_file $fileNew" `
                 -RedirectStandardOutput '.\console.out' -RedirectStandardError '.\console.err'
            }
        }
    Write-Host "End minification of JS files"
    
    
    #Second find everything we have a minified js version of, create an object of their names and paths, and delete the non-min file
    Write-Host "Beginning Removal of files...will display below"
    $minFiles = Get-ChildItem -Path ./* -Filter *.min.js -Recurse 
    foreach ($file in $minFiles)
        {
            #if ($file.FullName.Replace(".min.js", ".js") exists) {
            $private:nonMinifiedVersionFull = $file.FullName -replace ".min.js", ".js" #.ToString().Replace(".min.js", ".js")
            $private:nonMinifiedVersion = $file -Replace ".min.js", ".js" #.ToString().Replace(".min.js", ".js")
            Write-Host "  Removing: " $private:nonMinifiedVersion
            if ($debug -eq $false) {Remove-Item $private:nonMinifiedVersionFull -ErrorAction SilentlyContinue}
    
        $temp = New-Object System.Object
        $temp | Add-Member -MemberType NoteProperty -Name "minFileName" -Value $file.ToString()
        $temp | Add-Member -MemberType NoteProperty -Name "minFileFullName" -Value $file.FullName.ToString()
        $temp | Add-Member -MemberType NoteProperty -Name "maxFileName" -Value $private:nonMinifiedVersion.ToString()
        $temp | Add-Member -MemberType NoteProperty -Name "maxFileFullName" -Value $private:nonMinifiedVersionFull.ToString()
        $fileCollection.Add($temp) | Out-Null
        }
    Write-Host "End Removal of Files"
    
    if ($debug -eq $true) {
       Write-Host "The fileCollection is:"
       $fileCollection
       }
    
    Write-Host "Beginning update of references to point to minified"
    #now go through all the files that could reference them and update the references
    foreach ($file2 in $filesContainingResourceRefs)
        {
            $private:file = $file2.FullName
    
                $fixedContent = [System.IO.File]::ReadAllText($private:file)
    
                #Now loop through all the min and max files in the collection
               foreach ($line in $fileCollection) {
    
                        $strFind    = $line.maxFileName.ToString()
                        $strReplace = $line.minFileName.ToString()
    
                        $fixedContent = $fixedContent.replace($strFind, $strReplace)
    
                }            
                if ($debug -eq $false) {[System.IO.File]::WriteAllText($private:file, $fixedContent)}
    
    
               Write-Host "  Replaced non-minified references in: " $private:file
    
        }
    
    Write-Host "End update of references to point to minified"
    

    【讨论】:

      猜你喜欢
      • 2021-04-26
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 2023-03-13
      • 2014-06-12
      相关资源
      最近更新 更多