Page 1 of 1

PbTerser (Compress JavaScript)

Posted: Sun Apr 26, 2020 8:30 pm
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