[Pas2js] Javascript import and export

Michael Van Canneyt michael at freepascal.org
Mon Jul 5 05:44:22 CEST 2021



On Mon, 5 Jul 2021, Ng Pheng Siong wrote:

> 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:
>
> 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?

Your directive will not be possible since asm blocks are not parsed but 
copied as-is. Also, at some future point we also may want to parse the 
actual javascript (FPC has a parser for it), and then the directive will 
get in the way.

But better yet, it will simply not be necessary. We want to avoid asm altogether.

The plan is to translate the existing $linklib directive, like this one:

{$linklib atom}

to an import/require statement that will be prepended to the javascript file.
There will be statements in the JS or system unit which will allow you
retrieve the imported objects.

I will try to document in the WIKI what has been discussed, there is more
than what I wrote here.

But if you want to use import statements already today, this is easily done. 
simply look at the demos for VSCode and Atom plugins. 
They just require a small js file which is prepended/appended to the compiler
output, look for the packageglue.js file, which is appended with -Ja or
prepended with -Ji.

I have published the article I wrote about this technique for Blaise Pascal
magazine. See here:

https://www.freepascal.org/~michael/articles/index.html#atomvscode

The sources are in subversion, demo/atom, demo/vscode

Michael.


More information about the Pas2js mailing list