Juan Tarquino
Juan Tarquino

Reputation: 987

How to expose F# module's public functions to Javascript via Fable?

Let's say I have the following f# module:

module Sample =
    let Add x y = x + y
    let Subtract x y = x - y

How do I configure Fable or Webpack so that when I include the bundle.js file generated by webpack into my index.html, I can call the module Sample's functions from javascript, like this:

<script>
   var myResult = Sample.Add(2,4)
</script>

Thank you!

Upvotes: 1

Views: 232

Answers (1)

Maxime Mangel
Maxime Mangel

Reputation: 2006

First, you need to set up webpack to generate a "library".

In your webpack.config.js your output node should look like that:

    output: {
        path: resolve('./output'),
        filename: '[name].js',
        libraryTarget: 'var',
        library: 'EntryPoint'
    },

Then in order to expose a clean API to call from JavaScript, you should use an interface.

type Sample =
    abstract Add : int -> int -> int
    abstract Subtract : int -> int -> int

let private add x y = x + y

let api =
    { new Sample with
        member __.Add x y = add x y // You can call a local function
        member __.Subtract x y = x - y // You can implement the function directly in the interface 
    }

Then from JavaScript you can do something like that:

EntryPoint.api.Add(1, 2)
EntryPoint.api.Subtract(1, 2)

Upvotes: 5

Related Questions