[Pas2js] Javascript import and export

Ng Pheng Siong ngps at objectmemetic.com
Mon Jul 5 04:53:40 CEST 2021


On Sun, Jul 04, 2021 at 07:43:24PM +0200, Michael Van Canneyt wrote:
> > Will pas2js support import and export? What would the Pascal syntax look like?
> Import works, it is simply a unit.

Hi Michael,

For React Native and NativeScript, a main program in Javascript looks like this:

  /*
  In NativeScript, the app.js file is the entry point to your application.
  You can use this file to perform app-level initialization, but the
  primary purpose of the file is to pass control to the app’s first module.
  */
  import { Application } from '@nativescript/core';
  Application.run({ moduleName: 'app-root' })

Above is the Javascript main program generated by NativeScript's Hello
World-ish app template.

I tried this Pascal equivalent:

  program app;
  begin
    asm
      import { Application } from '@nativescript/core';
      Application.run({ moduleName: 'app-root' })
    end;
  end.

pas2js compiles the program, but NativeScript's Javascript engine fails to
run the program due to this error:

  ERROR in ./app/app.js 2205:4
  Module parse failed: 'import' and 'export' may only appear at the top level (2205:4)

So I moved the import statement to the top of the pas2js-generated app.js.
Here's the hand-modified version:

  // Below import added by hand.
  import { Application } from '@nativescript/core';

  var pas = {};
  var rtl = {
    // rtl stuff untouched
  }
  // various rtl modules untouched
  rtl.module("program",["System"],function () {
    "use strict";
    var $mod = this;
    $mod.$main = function () {
      // No import statement here.
      Application.run({moduleName:'app-root'});
    };
  });
  rtl.run();

The rest of the app's Javascript code as generated by the NativeScript
template is not modified. With this kludge, NativeScript successfully runs
the program on my computer's Android and iOS emulators.

With this, I think using pas2js to write NativeScript and/or React Native
apps has promise and is worth pursuing.

So I'm looking for Pascal syntax (or maybe compiler directive) to express
the need to place Javascript import statements at the top level of
pas2js-generated Javascript file. Something like this?

  program app;
  begin
    asm
      {$modeswitch toplevel+}
      import { Application } from '@nativescript/core';
      {$modeswitch toplevel-}

      Application.run({ moduleName: 'app-root' })
    end;
  end.

Where should I look in the compiler source to attempt to implement this
directive?

As for exports, the need comes when writing plugins for React
Native and NativeScript.

Pheng


More information about the Pas2js mailing list