OCaml compiler brings type safety to JavaScript

Web developers can use the OCaml language to write JavaScript code through the BuckleScript compiler, which has now gone to a 1.0 release. Open-sourced by news services provider Bloomberg, BuckleScript takes OCaml code and turns out JavaScript.

OCaml is a general-purpose language that supports imperative, functional, and object-oriented programming. “OCaml offers an industrial-strength state-of-the-art type system and provides very strong type inference (i.e. unlike TypeScript, no verbose type annotation is required), which proves invaluable in managing large projects,” Zhang said.

Internal benchmarking has BuckleScript compiling at least 10 times faster than TypeScript, Microsoft’s superset that compiles to plain JavaScript. "There is no magic here, the BuckleScript compiler is written in OCaml, which is compiled to blazing fast native code,” said Zhang. “However, it does not limit the availability of [the] BuckleScript compiler: it is also compiled to a JS file (gzipped: 700KB for pure OCaml + 300KB for Reason support).”

BuckleScript is intended to address large-scale problems with JavaScript, according to the compiler’s user manual. These include type safety, elimination of dead code, and offline optimizations. BuckleScript uses the OCaml type system and compiler implementation to optimize offline compilation and provide for fast runtime code. Loss of code structure is addressed by mapping one OCaml module onto one JavaScript module.

BuckleScript utilizes the OCaml compiler and toolchain to produce JavaScript closely resembling original Ocaml code, according to the project’s GitHub page. Name mangling is avoided, while stack traces are preserved. Programs can be compiled into native code, JavaScript, or a unikernel. The foreign function interface (FFI) in BuckleScript can model JavaScript objects natively. Some OCaml features highly coupled with runtimes, such as Gc and Unix modules, are not covered in BuckleScript.

Our Case Studies

IDG Connect delivers full creative solutions to meet all your demand generatlon needs. These cover the full scope of options, from customized content and lead delivery through to fully integrated campaigns.