BuckleScript

BuckleScript

  • Docs
  • Try
  • API
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Interop

Intro

  • What & Why
  • Installation
  • New Project
  • Try
  • Concepts Overview
  • Upgrade Guide to v7

Interop

  • Overview
  • Cheatsheet
  • Embed Raw JavaScript
  • Common Data Types
  • Intro to External
  • Bind to Global Values
  • Null, Undefined & Option
  • Object
  • Object 2
  • Class
  • Function
  • Property access
  • Return value wrapping
  • Import & Export
  • Regular Expression
  • Exceptions
  • JSON
  • Pipe First
  • Generate Converters & Helpers
  • Better Data Structures Printing (Debug Mode)
  • NodeJS Special Variables
  • Miscellaneous
  • Browser Support & Polyfills

Build System

  • Overview
  • Configuration
  • Automatic Interface Generation
  • Interop with Other Build System
  • Performance
  • Advanced

Standard Library

  • Overview

Advanced

  • Conditional Compilation
  • Extended Compiler Options
  • Use Existing OCaml Libraries
  • Difference from Native OCaml
  • Compiler Architecture & Principles
  • Comparison to Js_of_ocaml
Edit

Class

new

Use bs.new to emulate e.g. new Date():

type t
external createDate : unit -> t = "Date" [@@bs.new]

let date = createDate ()
type t;
[@bs.new] external createDate : unit => t = "Date";

let date = createDate();

Output:

var date = new Date();

You can chain bs.new and bs.module if the JS module you're importing is itself a class:

type t
external book : unit -> t = "Book" [@@bs.new] [@@bs.module]
let bookInstance = book ()
type t;
[@bs.new] [@bs.module] external book : unit => t = "Book";
let bookInstance = book();

Output:

var Book = require("Book");
var bookInstance = new Book();

Bind to JS Classes

JS classes are really just JS objects wired up funnily. In general, prefer using the previous object section's features to bind to a JS object.

OCaml having classes really helps with modeling JS classes. Just add a [@bs] to a class type to turn them into a Js.t class:

class type _rect = object
  method height : int [@@bs.set]
  method width : int [@@bs.set]
  method draw : unit -> unit
end [@bs]

type rect = _rect Js.t
class type _rect =
  [@bs]
  {
    [@bs.set] pub height: int;
    [@bs.set] pub width: int;
    pub draw: unit => unit
  };

type rect = Js.t(_rect);

For Js.t classes, methods with arrow types are treated as real methods (automatically annotated with [@bs.meth]) while methods with non-arrow types are treated as properties. Adding bs.set to those methods will make them mutable, which enables you to set them using #= later. Dropping the bs.set attribute makes the method/property immutable. Basically like the object section's features.

Last updated on 4/13/2020
← Object 2Function →
  • new
  • Bind to JS Classes