Getting Started



propertyicon.png Creating a new Pas2JS project

Creating a Pas2JS project has been completely automated in the development version of lazarus (see the Lazarus Integration section)The steps outlined here show how to do all the needed work manually.

Let's do a simple test. pas2js -?

Pas2JS Compiler version 1.5.1 [2019/07/29] for Win64 x86_64
Copyright (c) 2019 Free Pascal team.

Options:
Put + after a boolean switch option to enable it, - to disable it
  @   : Read compiler options from file  in addition to the default
            pas2js.cfg
  -B     : Rebuild all
  -d  : Defines the symbol . Optional: -d:=
  -i  : Write information and halt.  is a combination of the following:
    -iD  : Write compiler date
    -iSO : Write compiler OS
    -iSP : Write compiler host processor
    -iTO : Write target platform
    -iTP : Write target processor
    -iV  : Write short compiler version
    -iW  : Write full compiler version
    -ic  : Write list of supported JS processors usable by -P
    -io  : Write list of supported optimizations usable by -Oo
    -it  : Write list of supported targets usable by -T
    -iJ  : Write list of supported JavaScript identifiers -JoRTL-
  -C  : Code generation options.  is a combination of the following
            letters:
    o    : Overflow checking of integer operations
    r    : Range checking
    R    : Object checks. Verify method calls and object type casts.
  -F...   Set file names and paths:
   -Fe: Redirect output to file . UTF-8 encoded.
   -FE: Set main output path to 
   -Fi: Add  to include paths
   -FN: add  to namespaces. Namespaces with trailing - are removed.
            Delphi calls this flag "unit scope names".
   -Fu: Add  to unit paths
   -FU: Set unit output path to 
  -I  : Add  to include paths, same as -Fi
  -J...  Extra options of pas2js
   -Jc   : Write all JavaScript concatenated into the output file
   -Je: Encode messages as .
     -Jeconsole: Console codepage. This is the default.
     -Jesystem : System codepage. On non Windows console and system are the
            same.
     -Jeutf-8  : Unicode UTF-8. Default when using -Fe.
     -JeJSON   : Output compiler messages as JSON. Logo etc are outputted
            as-is.
   -Ji: Insert JS file  into main JS file. E.g. -Jirtl.js. Can be given
            multiple times. To remove a file name append a minus, e.g.
            -Jirtl.js-.
   -Jl   : lower case identifiers
   -Jm   : generate source maps
     -Jmsourceroot=: use x as "sourceRoot", prefix URL for source file
            names.
     -Jmbasedir=: write source file names relative to directory x, default
            is map file folder.
     -Jminclude: include Pascal sources in source map.
     -Jmabsolute: store absolute filenames, not relative.
     -Jmxssiheader: start source map with XSSI protection )]}', default.
     -Jm-: disable generating source maps
   -Jo: Enable or disable extra option. The x is case insensitive:
     -JoSearchLikeFPC: search source files like FPC, default: search case
            insensitive.
     -JoUseStrict: add "use strict" to modules, default.
     -JoCheckVersion-: do not add rtl version check, default.
     -JoCheckVersion=main: insert rtl version check into main.
     -JoCheckVersion=system: insert rtl version check into system unit init.
     -JoCheckVersion=unit: insert rtl version check into every unit init.
     -JoRTL-=: set RTL identifier y to value z. See -iJ.
   -Jr Control writing of resource string file
     -Jrnone: Do not write resource string file
     -Jrunit: Write resource string file per unit with all resource strings
     -Jrprogram: Write resource string file per program with all used
            resource strings in program
   -Jpcmd: Run postprocessor. For each generated js execute command
            passing the js as stdin and read the new js from stdout. This
            option can be added multiple times to call several postprocessors
            in succession.
   -Ju: Add  to foreign unit paths. Foreign units are not compiled.
   -JU: This pas2js does not support PCU files
  -l     : Write logo
  -MDelphi: Delphi 7 compatibility mode
  -MObjFPC: FPC's Object Pascal compatibility mode (default)
  -NS : obsolete: add  to namespaces. Same as -FN
  -n     : Do not read the default config files
  -o  : Change main JavaScript file to , "." means stdout
  -O  : Optimizations:
    -O-  : Disable optimizations
    -O1  : Level 1 optimizations (quick and debugger friendly)
    -Oo: Enable or disable optimization. The x is case insensitive:
      -OoEnumNumbers[-]: write enum value as number instead of name. Default
            in -O1.
      -OoRemoveNotUsedPrivates[-]: Default is enabled
      -OoRemoveNotUsedDeclarations[-]: Default enabled for programs with -Jc
  -P  : Set target processor. Case insensitive:
    -Pecmascript5: default
    -Pecmascript6
  -S  : Syntax options.  is a combination of the following letters:
    a    : Turn on assertions
    c    : Support operators like C (*=,+=,/= and -=)
    d    : Same as -Mdelphi
    m    : Enables macro replacements
    2    : Same as -Mobjfpc (default)
  -SI  : Set interface style to 
    -SIcom  : COM, reference counted interface (default)
    -SIcorba: CORBA interface
  -T  : Set target platform
    -Tbrowser: default
    -Tnodejs : add pas.run(), includes -Jc
  -u  : Undefines the symbol 
  -v  : Be verbose.  is a combination of the following letters:
    e    : Show errors (default)
    w    : Show warnings
    n    : Show notes
    h    : Show hints
    i    : Show info
    l    : Show line numbers, needs -vi
    a    : Show everything
    0    : Show nothing (except errors)
    b    : Show file names with full path
    c    : Show conditionals
    t    : Show tried/used files
    d    : Show debug notes and info, enables -vni
    q    : Show message numbers
    x    : Show used tools
    v    : Write pas2jsdebug.log with lots of debugging info
    z    : Write messages to stderr, -o. still uses stdout.
  -vm,: Do not show messages numbered  and .
  -?     : Show this help
  -h     : Show this help

Environment variable PAS2JS_OPTS is parsed after default config and before
            command line parameters.

Macros: Format is $Name, $Name$ or $Name()
  $Pas2jsFullVersion: major.minor.release
  $Pas2jsVersion: major.minor.release
  $CfgDir: Use within a config file. The directory of this config file
  $Env(): environment variable, e.g. $Env(HOME)

The pas2js command-line arguments are kept mostly the same as the FPC command-line arguments. Error messages are also in the same format. The compiler needs access to all sources, and so you need to specify the path to the sources of all used units. As for the FPC compiler, a configuration file is supported, which has the same syntax as the FPC config file. Basically, the command is the same as any FPC command line. The only thing that is different is the target: browser or node.js

propertyicon.png Hello World

Now, let's just create a simple delphi based project with a single unit as shown at the following example:

Hello World
program Project1; uses JS, Web, Classes, SysUtils, Unit1; var app: TApp; str: String; begin app:= TApp.Create; str := app.EncryptStr('warleyalex', 2); WriteLn(str); WriteLn( app.DecryptStr('îÂäØÊòÂØÊð', 2) ); //warleyalex end. //----------------------------------------------------- unit Unit1; interface type TApp = class(TObject) function EncryptStr(const S: String; Key: Integer): String; function DecryptStr(const S: String; Key: Integer): String; end; implementation function TApp.EncryptStr(const S: String; Key: Integer): String; var I: Integer; fuck: string; begin for I := 1 to Length(S) do begin fuck := fuck + chr(ord(S[I]) * key); end; Result := fuck; end; function TApp.DecryptStr(const S: String; Key: Integer): String; var I: Integer; fuck : string; begin for I := 1 to Length(S) do begin fuck := fuck + chr(ord(S[I]) div key) // DIV the char end; Result := fuck; end; end.

Here is how to compile:

pas2js -Jc -Jirtl.js  project1.dpr

When compiled succesfully, the code can be run in the browser by opening a html file in the browser with the following content:

<html>
  <head>
    <meta charset="utf-8"/>
    <script type="application/javascript" src="project1.js"></script>
  </head>
  <body>
    <script type="application/javascript">
	  window.addEventListener("load", rtl.run);
    </script>
  </body>
</html>

For node.js, the compiler will insert the call to rtl.run() automatically at the end of the generated Javascript file. The pas2js RTL is still in flux. There is a basic Object Pascal RTL, several units from the FPC Packages are also available:

  • system
  • sysutils
  • Math
  • strutils
  • rtlconst
  • classes
  • contnrs
  • DB (yes, TDataset)
  • fpcunit testsuite
  • custapp
  • restconnection
  • js (javascript system objects)
  • web (browser provided objects)
  • libjquery (jquery is available too)
  • nodejs (basic node runtime environment)
  • typinfo
  • objpas
  • browserconsole (support writeln)
  • dateutils
  • browserapp
  • nodejsapp

propertyicon.png JS file size

Why is a simple hello world program so big?

This is mainly due to the used rtl.js. The rtl.js contains code for Pascal modules, classes, RTTI, sets, range checks, etc and is written with big WebApps in mind, not for scripts with a few lines of code.

  1. You can use a Javascript minifier to reduce the created Javascript
  2. You can create your own minified rtl.js by removing all functions you don't need. Eventually this will be done automatically by pas2js.