PbTerser (Compress JavaScript)

Share your advanced knowledge/code with the community.
User avatar
Peter
Posts: 1086
Joined: Mon Feb 24, 2014 10:17 pm
Location: 127.0.0.1:9080
Contact:

PbTerser (Compress JavaScript)

Post by Peter »

Hello folks,

as long as JavaScript compression is disabled in SpiderBasic, you could use the following small tool for compression.

To use it, proceed as follows:

* If not already available: Install NodeJs (https://nodejs.org/en/) (there is a NodeJs available in the SpiderBasic installation package, but I couldn't get it to work for this purpose).

* Type the following in the command line: npm install terser -g

* Compile the source below with PureBasic as PbTerser.exe

* In the Create App - Dialog enter the PbTerser.exe as Commandline under "Post processing". The JavaScript file that SpiderBasic generates is entered as the Argument. The whole thing should look like this:

Image


After SpiderBasic has generated the app, PbTerser compresses the resulting JavaScript and shows how many bytes the file has been reduced by:

Image

Code: Select all

EnableExplicit

#AppName = "PbTerser"

Procedure Compress(InputJs.s, OutputJs.s)
  
  Protected Dummy.s
  
  Protected FileLengthBefore = FileSize(InputJs)
  
  Protected Terser = RunProgram("cmd.exe", "/c terser --compress --mangle --output " + Chr(34) + OutputJs + Chr(34) + " -- " + Chr(34) + InputJs + Chr(34), "", #PB_Program_Open | #PB_Program_Read | #PB_Program_Error | #PB_Program_Hide)
  
  Protected RPE.s ; ReadProgramError
  Protected RPS.s ; ReadProgramString
  Protected Exitcode
  
  If Terser
    
    While ProgramRunning(Terser)
      
      Dummy = ReadProgramError(Terser)
      
      If Dummy 
        RPE + Dummy + #CRLF$
      EndIf
      
      Dummy = ReadProgramString(Terser)
      
      If Dummy 
        RPS + Dummy + #CRLF$
      EndIf
      
    Wend
    
    Exitcode = ProgramExitCode(Terser)
    
    CloseProgram(Terser) ; Close the connection to the program
    
  EndIf
  
  Protected FileLengthAfter = FileSize(OutputJs)
  
  Protected Output.s
  
  If RPS <> ""
    Output + "ReadProgramString: " + #CRLF$ + RPS + #CRLF$
  EndIf
  
  If RPE <> ""
    Output + "ReadProgramError: " + #CRLF$ + RPE + #CRLF$
  EndIf
  
  If Exitcode <> 0
    Output + "ExitCode: " + Exitcode  + #CRLF$
  EndIf
  
  Output + "Filelength (before): " + FileLengthBefore + " bytes" + #CRLF$
  Output + "Filelength (after): "  + FileLengthAfter  + " bytes" + #CRLF$
  Output + "Saved size: " + Str(FileLengthBefore - FileLengthAfter) + " bytes" + #CRLF$
  
  MessageRequester(#AppName, Output)
  
EndProcedure

Define InputJs.s  = ProgramParameter(0)
Define OutputJs.s = InputJs

If FileSize(InputJs) > 0
  
  Compress(InputJs, OutputJs)
  
Else
  
  MessageRequester(#AppName, "File not found: '" + InputJs + "'")
  
EndIf
Have fun ... Peter