在发布到AWS S3之前,如何压缩/ gzip我的模拟.js和.css文件?

9 css powershell gzip amazon-s3 amazon-web-services

我运行了Google的pagespeed,它建议压缩我的.js和.css

在上面的内容中消除渲染阻止JavaScript和CSS显示如何修复

Enable compression
Compressing resources with gzip or deflate can reduce the number of bytes sent over the network.
Enable compression for the following resources to reduce their transfer size by 210.9KiB (68% reduction).
Compressing http://xx.com/content/bundles/js.min.js could save 157.3KiB (65% reduction).
Compressing http://xx.com/content/bundles/css.min.css could save 35.5KiB (79% reduction).
Compressing http://xx.com/ could save 18.1KiB (79% reduction).
Run Code Online (Sandbox Code Playgroud)

在我发布的过程中,我有一个步骤,使用Windows Powershell将.js和.css模拟的bundle移动到S3,然后转到cloudfront.

我可以在PowerShell脚本中添加一些可以压缩.js和.css文件的步骤吗?

此外,一旦文件被压缩,那么我是否必须做更多的事情而不是更改名称,以便告诉我的浏览器它需要尝试接受gzip文件?

Die*_*rán 6

您可以向上传脚本添加gzip压缩文件所需的代码.

一些示例代码可能是这样的:

function Gzip-FileSimple
{
    param
    (
        [String]$inFile = $(throw "Gzip-File: No filename specified"),
        [String]$outFile = $($inFile + ".gz"),
        [switch]$delete # Delete the original file
    )

    trap
    {
        Write-Host "Received an exception: $_.  Exiting."
        break
    }

    if (! (Test-Path $inFile))
    {
        "Input file $inFile does not exist."
        exit 1
    }

    Write-Host "Compressing $inFile to $outFile."

    $input = New-Object System.IO.FileStream $inFile, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read)

    $buffer = New-Object byte[]($input.Length)
    $byteCount = $input.Read($buffer, 0, $input.Length)

    if ($byteCount -ne $input.Length)
    {
        $input.Close()
        Write-Host "Failure reading $inFile."
        exit 2
    }
    $input.Close()

    $output = New-Object System.IO.FileStream $outFile, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None)
    $gzipStream = New-Object System.IO.Compression.GzipStream $output, ([IO.Compression.CompressionMode]::Compress)

    $gzipStream.Write($buffer, 0, $buffer.Length)
    $gzipStream.Close()

    $output.Close()

    if ($delete)
    {
        Remove-Item $inFile
    }
}
Run Code Online (Sandbox Code Playgroud)

从这个站点:在Powershell中创建Gzip


Mat*_*oSp 5

Powershell社区扩展有一个用于gzipping文件的scriptlet,它非常易于使用:

Write-Gzip foo.js #will create foo.js.gz
mv foo.js.gz foo.js -Force
Run Code Online (Sandbox Code Playgroud)

您不必重命名文件,只需添加Content-Encoding标题并将其设置为gzip.