B4J Library [Web] [B4X] MiniJS

Version 0.60
GitHub: https://github.com/pyhoon/MiniJs-B4X

MiniJS-B4X is a B4X library that allows you to generate JavaScript code programmatically from your B4X applications. It provides a fluent API for building JavaScript code structures including functions, loops, conditionals, variables, objects, arrays, and more.

Features​

  • Fluent API - Chainable methods for building JavaScript code
  • Code Generation - Generate functions, loops, conditionals, variables, objects, arrays
  • Indentation Management - Automatic indentation handling
  • Comments Support - Single-line, multi-line, and inline comments
  • Control Structures - Functions, if/else, for loops, try/catch
  • Variables - const/let declarations with optional initialization
  • Objects & Arrays - Object literals and array literals
  • Function Calls - Method calls and function calls with arguments
  • Event Listeners - Event listener generation
  • Custom Events - CustomEvent dispatching
  • Template Literals - Template string support

Installation​

  1. Copy MiniJS.b4xlib from the release folder to your B4X additional libraries folder
  2. In B4X IDE Libraries Manager tab, check the MiniJS library

Example:
B4X:
Sub Process_Globals
    Private jsGen As MiniJS
End Sub

Sub AppStart (Args() As String)
    jsGen.Initialize
  
    ' Generate a sample function
    GenerateSampleFunction
  
    ' Get generated code with script tags
    Dim jsCode As String = jsGen.Generate
  
    ' Or without script tags
    Dim jsCodeRaw As String = jsGen.Generate2
  
    Log(jsCode)
End Sub

Private Sub GenerateSampleFunction
    jsGen.AddMultiLineComment("Sample generated JavaScript function" & CRLF & "Generated by B4J")
  
    ' Start function: function calculateTotal(items, taxRate) {
    jsGen.StartFunction("calculateTotal", Array As String("items", "taxRate"))
  
    ' let subtotal = 0;
    jsGen.DeclareVariable("subtotal", "0", False)
  
    ' for (let i = 0; i < items.length; i++) {
    jsGen.StartForLoop("let i = 0", "i < items.length", "i++")
  
    '     subtotal += items[i].price;
    jsGen.AddLine("subtotal += items[i].price;")
  
    ' }
    jsGen.EndForLoop
  
    ' if (taxRate > 0) {
    jsGen.StartIf("taxRate > 0")
  
    '     const tax = subtotal * taxRate;
    jsGen.DeclareVariable("tax", "subtotal * taxRate", True)
  
    '     return subtotal + tax;
    jsGen.AddLine("return subtotal + tax;")
  
    ' } else {
    jsGen.AddElse
  
    '     return subtotal;
    jsGen.AddLine("return subtotal;")
  
    ' }
    jsGen.EndIf
  
    ' }
    jsGen.EndFunction
End Sub

Output:
JavaScript:
    /*
     * Sample generated JavaScript function
     * Generated by B4J
     */
    function calculateTotal (items, taxRate) {
        let subtotal = 0;
        for (let i = 0; i < items.length; i++) {
            subtotal += items[i].price;
        }
        if (taxRate > 0) {
            const tax = subtotal * taxRate;
            return subtotal + tax;
        } else {
            return subtotal;
        }
    }

API Reference​

Initialization​

MethodDescription
InitializeInitialize the generator

Code Generation​

MethodDescription
Generate As StringGenerate complete JS code wrapped in script tags
Generate2 As StringGenerate complete JS code without script tags

Indentation​

MethodDescription
IncreaseIndentIncrease indentation level
DecreaseIndentDecrease indentation level

Comments​

MethodDescription
AddComment(comment As String)Add single-line comment
AppendComment(comment As String)Append comment to current line
AddMultiLineComment(comment As String)Add multi-line comment block
AddNewLineAdd blank line

Functions​

MethodDescription
StartFunction(name As String, parameters() As String)Start function declaration
EndFunctionEnd function declaration

Control Flow​

MethodDescription
StartIf(condition As String)Start if statement
ElseIf(condition As String)Add else if clause
AddElseAdd else clause
EndIfEnd if statement
StartForLoop(initializer, condition, increment)Start for loop
EndForLoopEnd for loop
StartTryStart try block
AddCatch(event As String)Add catch block
EndTryEnd try/catch block

Variables​

MethodDescription
DeclareVariable(name, value, isConst)Declare const/let variable

Objects & Arrays​

MethodDescription
CreateObject(name, properties As Map)Create object literal
CreateArray(name, items As List)Create array literal

Function & Method Calls​

MethodDescription
AddFunctionCall(functionName, args())Call function
AddMethodCall(objectName, methodName, args())Call method on object

Events​

MethodDescription
AddEventListener(functionName, eventName)Add event listener
AddCustomEventDispatch(eventName, detailData As Map)Dispatch custom event

Console​

MethodDescription
ConsoleLog(message)Generate console.log()
ConsoleError(message, event)Generate console.error()

Conditionals​

MethodDescription
AddConditionalCall(condition, call)Inline conditional call
AddTernary(condition, trueExpr, falseExpr)Ternary operator
 

Attachments

  • MiniJS.b4xlib
    3.2 KB · Views: 156
Last edited:

aeric

Expert
Licensed User
Longtime User
Version 0.30

What's New​

  1. Added Generate2 sub --> No script tags
  2. Added IncreaseIndent and DecreaseIndent sub
  3. Renamed Else sub to AddElse
 

aeric

Expert
Licensed User
Longtime User
Version 0.40

What's New​

  1. Added ConsoleError sub
  2. Added ConsoleLog sub
  3. Added StartTry sub
  4. Added AddCatch sub
  5. Added EndTry sub
  6. Removed StartCondition sub
  7. Removed EndCondition sub
  8. Changed AddMethodCall sub not to return value
 
Top