Bucklescript

Weeeelll’p, I made a brunch plugin for Bucklescript. Bit of a hack since I do not know how to use stdin/stdout with bsc (might be fixed soon), but it works and is glorious.

Given a brunch plugin config of:

  plugins: {
    bucklescriptBrunch: {
      // Commented out means use the bucklescript compiler on the global path, soon
      // I will have it default to the one in node_modules once the next version that adds
      // Windows support is released.
      // binPath: "",

      // This is the base directory of your own ocaml files
      bscCwd: "src",

      // Where to put the temporary build files, this should not be a placed that is watched
      // by Brunch or it can grab some javascript that it should not, it defaults to this:
      // tempOutputFolder: "tmp",

      // Additional parameters, to the compiler if wanted
      bscParameters: [
        "-bs-cross-module-opt"
      ]
    }
  },

  modules: {
    autoRequire: {
      'app.js': ['src/main_entry.ml'],
    },
  },

And given the file src/fib.ml:

let fib n  =
  let rec aux n a b =
    if n = 0 then a
    else
      aux (n - 1) b (a+b)
  in aux n 1 1

And given the file src/main_entry.ml:

let res =
  for i = 0 to 10 do
    Js.log (Fib.fib i)
  done

It generates into app.js pre-minification of:

// snip brunch header javascript for the javascript module system

require.register("src/fib.ml", function(exports, require, module) {
// Generated by BUCKLESCRIPT VERSION 1.0.2 , PLEASE EDIT WITH CARE
'use strict';


function fib(n) {
  var _n = n;
  var _a = 1;
  var _b = 1;
  while(true) {
    var b = _b;
    var a = _a;
    var n$1 = _n;
    if (n$1) {
      _b = a + b | 0;
      _a = b;
      _n = n$1 - 1 | 0;
      continue ;
      
    }
    else {
      return a;
    }
  };
}

exports.fib = fib;
/* No side effect */

});

;require.register("src/main_entry.ml", function(exports, require, module) {
// Generated by BUCKLESCRIPT VERSION 1.0.2 , PLEASE EDIT WITH CARE
'use strict';

var Fib = require("./fib");

for(var i = 0; i <= 10; ++i){
  console.log(Fib.fib(i));
}

var res = /* () */0;

exports.res = res;
/* res Not a pure module */

});

;require.register("___globals___", function(exports, require, module) {
  
});})();require('___globals___');

require('src/main_entry.ml');
//# sourceMappingURL=app.js.map

Which of course prints out to the console:

1
1
2
3
5
8
13
21
34
55
89
2 Likes