Wednesday, June 17, 2015

Minify CSS and JS files through PowerShell scripts

The below scripts can be used in scenarios where you need to minify CSS and JavaScript files of your website using PowerShell Scripts. (For example, during Post-build PowerShell scripts in TFS build).

Pre-requisite:
Microsoft Ajax Minifier should be installed on the machine (or TFS build server) where the PowerShell scripts would be executing.
Ajax Minifier can be downloaded from here.

PowerShell scripts to minify CSS files in a directory:

function applyCssMinification($dir)
{
$Minifier = “C:\Program Files (x86)\Microsoft\Microsoft Ajax Minifier\AjaxMin.exe”
get-childitem $dir -recurse -force -include *.css -exclude *.min.css | foreach-object {&$Minifier $_.FullName -out $_.FullName -clobber}

}

PowerShell scripts to minify JavaScript files in a directory:

function applyJsMinification($dir)
{
$Minifier = “C:\Program Files (x86)\Microsoft\Microsoft Ajax Minifier\AjaxMin.exe”
get-childitem $dir -recurse -force -include *.js -exclude *.min.js | foreach-object {&$Minifier $_.FullName -out $_.FullName -clobber}
}

Once defined call these functions by providing CSS and JS directory path as a parameter:

For example,

applyCssMinification "$Env:TF_BUILD_SOURCESDIRECTORY\Website\Content\CSS"


applyJsMinification "$Env:TF_BUILD_SOURCESDIRECTORY\Website\Content\Scripts"

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman