最近在維護一個小后臺專案,有段JS需要壓縮上傳到CDN存盤服務器,由于之前壓縮的JS檔案都比較少,都是手動壓縮的,這次需要壓縮的檔案比較多,所以用了批量壓縮,特此記錄一下,方便大家和自己以后再用到的時候備忘,
v準備作業
安裝nodejs
首先在本地安裝node.js和npm,一般npm集成于nodejs,即安裝nodejs,同時也安裝了npm,node.js下載地址,下載以后直接不停下一步就行,全部使用默認選項即可,下載完成后打開CMD,node -v檢測是否安裝成功,安裝成功則會顯示nodejs版本號,
安裝uglify插件
在cmd命令列執行:npm install uglify-js -g
v開始壓縮
壓縮的時候將下面的代碼拷貝下來,然后生成bat檔案,再運行bat檔案(有些電腦可能需要windows管理員身份運行),然后依次輸入當前的JS檔案目錄,再輸入生成輸出壓縮后JS的目錄即可,
@ECHO OFF setlocal enabledelayedexpansion set source_path=%1 set target_dir=%2 IF [%1]==[] ( rem echo please input javascript file or directory set /p source_path=please input javascript file or directory: ) IF [%2]==[] ( rem echo please input output directory set /p target_dir=please input output directory: ) rem source path exists? FOR %%i IN (%source_path%) DO SET FileAttrib=%%~ai if "%FileAttrib%" equ "" ( rem not found file attribute, source path not exist echo source path ^(%source_path%^) doesn't exist exit /b 0 ) ELSE IF "%FileAttrib:~0,1%" equ "d" ( rem source path is directory and not end with \, append \ to source path IF %source_path:~-1% neq \ ( set source_path=%source_path%\ ) ) echo source path is %source_path% rem target path exists? FOR %%i IN (%target_dir%) DO SET fa=%%~ai IF [%fa%]==[] ( rem target path not exist, make it mkdir %target_dir% ) IF %target_dir:~-1% neq \ ( rem append \ to target path set target_dir=%target_dir%\ ) echo target path is %target_dir% IF [%FileAttrib:~0,1%]==[d] ( for /r %source_path% %%I in (*.js) do ( set file_name=%%~nI set parent=%%~dpI set target_parent=%target_dir%!parent:%source_path%=! if not exist !target_parent! mkdir !target_parent! cd !target_parent! if [!file_name:~-4!] neq [.min] ( set w= uglifyjs %%I -m -c -O ascii_only=true -o !target_parent!%%~nI.min.js rem uglify .js file echo uglifyjs from "%%I" to "!target_parent!%%~nI.min.js" start cmd /c "!w!" ) else ( rem copy min.js file echo copy file from "%%~dpnI.js" to "!target_parent!%%~nI.js" start cmd /c "copy %%~dpnI.js !target_parent!%%~nI.js" ) ) ) else ( for %%I in (%source_path%) do ( IF "%%~xI" EQU ".js" ( set file_name=%%~nI if [!file_name:~-4!] neq [.min] ( rem uglify .js file set val=%target_dir%%%~nI.min.js echo uglifyjs from "%%I" to "!val!" start cmd /c "uglifyjs %%I -m -c -O ascii_only=true -o !val!" ) else ( rem copy min.js file echo copy file from "%%I" to "%target_dir%%%~nI.js" start cmd /c "copy %%I %target_dir%%%~nI.js" ) ) ) ) echo done
v原始碼地址
https://github.com/toutouge/javademosecond/tree/master/hellolearn
作 者:請叫我頭頭哥
出 處:http://www.cnblogs.com/toutou/
關于作者:專注于基礎平臺的專案開發,如有問題或建議,請多多賜教!
著作權宣告:本文著作權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文鏈接,
特此宣告:所有評論和私信都會在第一時間回復,也歡迎園子的大大們指正錯誤,共同進步,或者直接私信我
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角【推薦】一下,您的鼓勵是作者堅持原創和持續寫作的最大動力!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/538567.html
標籤:JavaScript
