Powershell script & Node module to Minify the JS files within directories & its sub-directories

Tarun Kumar Chatterjee
.Net – Technology Specialist
Published On :   12 May 2018
Visit Count
Today :  4    Total :   526

Recently faced a requirement to search all the JS files from a visual studio solution, minify each & overwrite at the same location.

After some research I found a node component named as Uglify-JS to a achieve the functionality.

So, first I downloaded the Uglify-JS node component & which is placed to my local path: C:\Program Files\nodejs\node_modules\grunt-contrib-uglify\node_modules\uglify-js\bin\uglifyjs

Then, prepared a powershell script below to iterate each directory & its sub-directories specified in the input array, do the minification for each & overwrite to the same file.

 $arrayInput = ("C:\Projects\MinificationDemo\MinificationDemo\Scripts\", "C:\Users\Tarun\Desktop\test1", "C:\Users\Tarun\Desktop\test2") 
 foreach ($input in $arrayInput)
                 $folders =  Get-ChildItem -path $input -Recurse -include *.js
                 Foreach ($fldr in $folders)
                                 if($fldr.Attributes -ne 'Directory')
                                                 node " C:\Program Files\nodejs\node_modules\grunt-contrib-uglify\node_modules\uglify-js\bin\uglifyjs " --output $fldr.FullName  $fldr.FullName
                                                 Write-Host $fldr.FullName "has been minified."

Hope it will give the basic idea about how simply we can minify the JS files.

Happy Coding

Tarun Kumar Chatterjee