node.jsocamljs-of-ocaml

How to use properly compile OCaml programs with js_of_ocaml?


I want to translate the following Javascript example program in OCaml, using js_of_ocaml:

var AWS = require('aws-sdk');
AWS.config.region = 'us-west-2';
var s3 = new AWS.S3();
s3.listBuckets(function(err, data) {
  if (err) { console.log("Error:", err); }
  else {
    for (var index in data.Buckets) {
      var bucket = data.Buckets[index];
      console.log("Bucket: ", bucket.Name, ' : ', bucket.CreationDate);
    }
  }
});

I wrote the following OCaml snippet

let require_module s =
    Js.Unsafe.fun_call
      (Js.Unsafe.js_expr "require")
      [|Js.Unsafe.inject (Js.string s)|]

module AWS : sig
  type error

  class type s3 = object
    method listBuckets :
      (error -> Js.Unsafe.any -> unit) Js.callback -> unit Js.meth
  end

  val s3client : unit -> s3
end = struct
  let _js_aws = require_module "aws-sdk"

  type error =
    Js.Unsafe.any

  class type s3 = object
    method listBuckets :
      (error -> Js.Unsafe.any -> unit) Js.callback -> unit Js.meth
  end

  let s3client () =
    let constr_s3 = _js_aws ## S3 in
    new%js constr_s3 ()
end

but when I compile it with

ocamlfind ocamlc -c -package "js_of_ocaml js_of_ocaml.syntax" -o example_s3.cmo example_s3.ml

It dies with

Error: '##' is not a valid value identifier.

How can I fix my program or my compilation command to fix this?


Solution

  • If you want to use the package js_of_ocaml.syntax you must add the -syntax camlp4o option to ocamlfind.

    But you should use the new ppx syntax instead of the old camlp4 one (which you seem to know since you use new%js). For that you need to replace js_of_ocaml.syntax with the package for the ppx syntax.