#2004 Compiling to JS - How To?

davedes Wed 15 Aug 2012

Hey folks,

Just starting off with Fantom and I'm very impressed so far. However, I'm struggling to compile a simple example to JavaScript. I do not want to use a web server -- nor do I want to use the FWT/G2D stuff. For now I am only looking for bare-bones Fantom-to-JS compilation, for e.g. to access "document.getXXX" from Fantom.

However, the build (using this code) compiles to a .pod -- how can I get it to spit out a .js for anything tagged with @JS?

My dir structure:

test
  fan
    JSGL.fan
  js
    JSGLPeer.js
  build.fan

JSGL.fan

@Js
class JSContext {
  static Void main() {
    alert("Hello!")
  }

  native static Void alert(Str str)
}

JSGLPeer.js

fan.JSGL.JSContextPeer = fan.sys.Obj.$extend(fan.sys.Obj);
fan.JSGL.JSContextPeer.prototype.alert = function(self, msg) { alert(msg); }

andy Wed 15 Aug 2012

Hey @davedes - I'm about to run out the door - so can write more later - but read thru this chapter to get your feet wet: docLang::JavaScript

davedes Thu 16 Aug 2012

Thanks andy.

I checked out the article -- it seems to emphasize the use of web servers and dynamically generating the JavaScript code.

My problem is that the generated .js file inside of the .pod only includes the peer (JSGLPeer.js). How could I compile it together with the rest of the JSGL.fan script, so that, say, I could do the following from the HTML document:

window.onload = fan.JSGL.JSContext.main;

Ideally I'm looking for a solution that compiles JSGL and JSGLPeer into a single JS file that can be included like any other JavaScript utility.

I've had moderate success compiling Fantom to JavaScript using CompilerInput as described here, but that doesn't seem to take native methods into account.

andy Thu 16 Aug 2012

My problem is that the generated .js file inside of the .pod only includes the peer (JSGLPeer.js).

JavaScript is always generated statically at compile time. So the pod.js file is a complete self-contained file for that pod - which you should be able to use and run it anywhere. But you will need to parse any dependencies first ( sys in particular) for it to run properly.

The .pod file is just a zip file - so any off the shelf tool can open and extract that file - including sys::Pod.file or sys::Zip API.

I've had moderate success compiling Fantom to JavaScript using CompilerInput

You don't need to do anything besides annotate your class with @Js. The JavaScript compiler will automatically run if any types are marked with @Js.

davedes Fri 17 Aug 2012

Thanks, I'll try all of this. :) sys::Pod.file seems to be what I need.

Login or Signup to reply.